Triple single quote vs triple double quote in Ruby

北城以北 提交于 2019-12-01 04:55:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!