Search code examples
rubystring-literals

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?


Solution

  • 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/