Diversion: Double-Quoted Strings
So far, we’ve used only single-quoted strings. They
are the easiest to use, in the same sense that a
shovel is easier to use than a backhoe: when the job
gets big enough, it stops being easier.
Consider multiline strings:
buffy_quote_1 = ''Kiss rocks'? |
Why would anyone want to kiss... |
Oh, wait. I get it.' |
|
buffy_quote_2 = "'Kiss rocks'?
" + |
"Why would anyone want to kiss...
" + |
"Oh, wait. I get it." |
puts buffy_quote_1 |
puts |
puts(buffy_quote_1 == buffy_quote_2) |
'Kiss rocks'? |
Why would anyone want to kiss... |
Oh, wait. I get it. |
|
false |
Using double quotes, we can indent the strings so they
all line up. You’ll notice the “
”,
which is the escape sequence for the newline character. With
this, you can also put a multiline string on one line of code:
puts "3...
2...
1...
HAPPY NEW YEAR!" |
3... |
2... |
1... |
HAPPY NEW YEAR! |
But it doesn’t work with the simpler single-quoted strings:
puts '3...
2...
1...
HAPPY NEW YEAR!' |
3...
2...
1...
HAPPY NEW YEAR! |
And just as you must escape single quotes in single-quoted
strings (but not double quotes), you must escape double quotes in double-quoted
strings (but not single quotes):
puts 'single (') and double (") quotes' |
puts "single (') and double (") quotes" |
single (') and double (") quotes |
single (') and double (") quotes |
So, that’s double-quoted strings. In most cases, I prefer the
simplicity of single-quoted strings, honestly. But there’s one
thing that double-quoted strings do very nicely: interpolation.
It’s sort of a cross between string addition,
to_s conversion, and salsa. (The food
or the dance—pick whichever metaphor works best for you.)
name = 'Luke' |
zip = 90210 |
|
puts "Name = #{name}, Zipcode = #{zip}" |
Name = Luke, Zipcode = 90210 |
Snazzy, no? We got to use the variable names right in the
string, just by putting it inside “#{...}”.
And you’ll notice that we didn’t have to say
zip.to_s to convert the ZIP code to
a string; Ruby knows that you want it to be a string in this case,
so it does the conversion for you.
But it gets even better! You’re not limited to variables when
using string interpolation—you can use any expression you want!
Ruby evaluates the expression for you, converts to string, and
injects the result into the surrounding string:
puts "#{2 * 10**4 + 1} Leagues Under the Sea, THE REVENGE!" |
20001 Leagues Under the Sea, THE REVENGE! |
Good stuff. (Don’t say I never gave you nothing.)