Strings and String Literals

The two most common ways of specifying a string are in single and double quotes, and we've been doing both ever since Day 1. Often it doesn't matter which kind of quotes you choose:

"Parks and Recreation" == 'Parks and Recreation'  #->  true

The difference arises when you want to put something unusual in the string, such as a special character or an expression that should be evaluated. We have seen that \n produces a single newline character when enclosed in double quotes. When inside single quotes, though, it produces a backslash character and an n, as if the escape sequence had no particular meaning at all:

 cooked = "a\nb\nc\n" raw = 'a\nb\nc\n' cooked.length #-> 6 raw.length #-> 9 puts cooked # output: a b c puts ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.