Monday, November 7, 2011

Exercise 10: What Was That? Learn Ruby the Hard Way: Practicum

So in the last exercise, Zed showed us some new ways to get strings to appear
across multiple lines.  The first used a backslash and a characters 'n' together ('\n') to put a new line character into the string.

This is called an "escape sequence", and there are a number of ways to use them. The "back-slash" can also be used to print literal characters that otherwise would be used for command and syntax purposes, such as allowing us to print literal characters like ", ', or \ (we use \", \'. or \\ to show them in strings.

Here's an example Zed provides:

"I am 6'2\" tall."  # escape double-quote inside string
'I am 6\'2" tall.'  # escape single-quote inside string

I commented yesterday that there is a technique I've seen in Perl and used in CGI scripts (yes, I'm old enough to have written CGI :) ). Zed points out that this is referred to as "here" document syntax. Note: this displays weird in different browsers, so where you see the back slash, in this case, it's there so that I can print out what should be there, which is the two "less than" characters without the back slashes (see in the code snippets in the images if this is too confusing).

So let's check this out:

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = \<\
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass

puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat

[and here's my attempt, with some annotation as to what's going on]

What You Should See

Look for the tab characters that you made. In this exercise the spacing is important to get right.

$ ruby ex10.rb
    I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.
I'll do a list:
    * Cat food
    * Fishies
    * Catnip
    * Grass


[and I do see it :)]

Extra Credit

Search online to see what other escape sequences are available.

[ Below are some of the more common escape sequences that can appear inside of double quotes.
\" – double quote
\\ – single backslash
\a – bell/alert
\b – backspace
\r – carriage return
\n – newline
\s – space
\t – tab

There are certainly more

Combine escape sequences and format strings to create a more complex format.

[see below]


So this is pretty cool. There's a number of tools we can use to allow us to get text to appear in ways that are not just starting at the beginning of the line, or even inserting noises (if you are into that sort of thing ;) ). I now have a proper name (here document) for the \<\

1 comment:

Droz said...

Enjoying reading your solutions after doing the accompanying exercises!