Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple single quote vs triple double quote in Ruby

Tags:

ruby

escaping

Why might you use ''' instead of """, as in Learn Ruby the Hard Way, Chapter 10 Study Drills?

like image 477
Grace River Yu Avatar asked Dec 02 '22 15:12

Grace River Yu


2 Answers

There are no triple quotes in Ruby.

Two String literals which are juxtaposed are parsed as a single String literal. So,

'Hello' 'World'
#=> "HelloWorld"

is the same as

'HelloWorld'
#=> "HelloWorld"

And

'' 'Hello' ''
#=> "Hello"

is the same as

'''Hello'''
#=> "Hello"

is the same as

'Hello'
#=> "Hello"

Since adding an empty string literal does not change the result, you can add as many empty strings as you want:

""""""""""""'''''Hello'''''''''
#=> "Hello"

There are no special rules for triple single quotes vs. triple double quotes, because there are no triple quotes. The rules are simply the same as for quotes.

like image 89
Jörg W Mittag Avatar answered Dec 11 '22 06:12

Jörg W Mittag


I assume the author confused Ruby and Python, because a triple-quote will not work in Ruby the way author thought it would. It'll just work like three separate strings ('' '' '').

For multi-line strings one could use:

%q{
 your text
 goes here
}
 => "\n     your text\n     goes here\n    "

or %Q{} if you need string interpolation inside.

like image 35
mmln Avatar answered Dec 11 '22 06:12

mmln