rubilicious

Learn Ruby the Hard Way

by Zed Shaw

Example 10

Previous   Next

The variable tabby_cat is assigned the value of the string;
The \t (backslash t) tabs the line in

tabby_cat = "\tI'm tabbed in."

The variable persian_cat is assigned the value of the string;
The \n (backslash n) puts the rest of the string on a new line

persian_cat = "I'm split \non a line."

The variable backslash_cat is assigned the value of the string;
The \ (backslash backslash) prints a backslash character

backslash_cat = "I'm \\ a \\ cat."

The variable fat_cat is assigned the value of the list MY_HEREDOC.
This is a HEREDOC. The « symbol with a name written in uppercase acts like the «PARAGRAPH we used earlier. You can write as many lines as you want in between You can call it anything you want as long as you include the chevrons («) before and end it with the same name.
Heredoc - The term refers to a form of multiline string literals that preserve line breaks and other whitespace, including indentation, in the text.* Wikipedia

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

The puts method prints the variables

puts "cat"
puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat

The same effect as the heredoc can be achieved with a triple "

fattest_cat =
"""
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
puts fattest_cat

$ ruby ex10.rb returns:

ESCAPE SEQUENCES & FORMAT STRINGS
  I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.
Things to Buy for the Cats:
  * Cat Food
  * Fish
  * Catnip
  * Grass