The Solution2:12 with Jay McGavren
Now that you've coded your solution to the practice problem, I'll show you how I did it.
Here's my code:
puts 'When you include \t in a double-quoted string in Ruby, it looks like this:' puts "before\tafter" puts 'When you include \n in a double-quoted string, it looks like this:' puts "before\nafter"
Your goal was to create a simple tutorial that showed various escape sequences and 0:00 how they looked in Ruby output. 0:04 Here's my solution, it's okay if yours is slightly different, but 0:06 if you see something interesting in my code you should consider borrowing it to 0:09 improve your own program. 0:12 So for each line where I need to show what an escape sequence looks like in code, 0:16 it's a bit of a pain to have to escape the \. 0:20 So what I did was, I put those lines in single quoted strings. 0:23 That way when I put /t, it puts that literal value, /t, into the output. 0:28 Then, for lines where I need to show what the escape sequence actually looks like 0:36 in output, I put the escape sequence in double quoted strings. 0:40 That way it gets interpolated into the string and 0:44 it appears as a tab character in the output. 0:46 Same thing for the new line escape sequence. 0:50 Here I put it in a single quoted string, and down here I put it in a double quoted 0:53 string so that we wind up with an actual new line character in the output. 0:57 An alternate solution might be to put the whole string in a Ruby here document. 1:01 A here document basically gets treated as one big double quoted string. 1:06 we need to escape the backslash by putting a double backslash here, and 1:11 that will appear as a single backslash in the output. 1:14 Then on the following line when we need to show what \t looks like in output, we just 1:18 put the escape sequence \t and that will be replaced with the tab character. 1:22 Same thing for the new lines, 1:28 we use a \\n to make a backslash followed by n to appear in the output. 1:29 And we actually don't have to use an escape sequence since we're using 1:35 a Here Document. 1:39 Here Documents are meant for showing output that flows over multiple lines. 1:40 So we just put a literal new line character in our code, and 1:43 that will show up in the output. 1:46 Either way you chose to solve this problem, 1:49 I hope you got in some good Ruby practice. 1:51 Feel free to add on to your finished program if you want. 1:53 For example, you might experiment with some additional Ruby escape sequences. 1:57 I'll have a link to more information about those in the teacher's notes. 2:01 You could try including single quotes in a single quoted string, 2:05 double quotes in a double quoted string, or backslashes in any string, have fun. 2:07
You need to sign up for Treehouse in order to download course files.Sign up