Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learn Ruby The Hard Way Chapter 9 Triple Quotes

Zed Shaw's Learn Ruby the Hard Way chapter 9 uses triple double quotes:

puts """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""

I tried writing the same thing with single double quotes and it seems to work fine. I don't understand the difference between triple and single double quotes. Am I missing something?

like image 384
JohnsWort Avatar asked Jan 16 '15 08:01

JohnsWort


2 Answers

I don't know why he uses triple double quotes in his book. They're nothing special, and one double quote works just fine.

This is a little known "feature" of ruby - it simply glues adjacent strings together.

s = "hello " "world" # equivalent to "hello " + "world"
s # => "hello world"

So your example is equivalent to

puts "" + "
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
" + ""

More string tricks: http://pivotallabs.com/stupid-ruby-quoting-tricks/

like image 148
Sergio Tulentsev Avatar answered Nov 04 '22 02:11

Sergio Tulentsev


I think you found a mistake in the book - the reason he uses triple quotes may be that Python allows you to write strings over multiple lines only when using triple quotes, so it might have been that he took over the example from "Learning Python the Hard Way" or simply mixed up languages.

In Ruby, you can include new lines even in single quotes.

Let him know about that, I'm sure he'll appreciate it.

like image 45
Beat Richartz Avatar answered Nov 04 '22 02:11

Beat Richartz