问题
Why might you use '''
instead of """
, as in Learn Ruby the Hard Way, Chapter 10 Study Drills?
回答1:
There are no triple quotes in Ruby.
Two String
literals which are juxtaposed are parsed as a single String
literal. So,
'Hello' 'World'
is the same as
'HelloWorld'
And
'' 'Hello' ''
is the same as
'''Hello'''
is the same as
'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.
回答2:
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.
回答3:
Triple-quotes '''
are the same as single quotes '
in that they don't interpolate any #{}
sequences, escape characters (like "\n"), etc.
Triple-double-quotes (ugh) """
are the same as double-quotes "
in that they do interpolation and escape sequences.
This is further down on the same page you linked.
The triple-quoted versions """
''''
allows for multi-line strings... as does the singly-quoted '
and "
, so I don't know why both are available.
来源:https://stackoverflow.com/questions/28511229/triple-single-quote-vs-triple-double-quote-in-ruby