简体   繁体   English

单引号与双引号

[英]Single quotes vs double quotes

I am trying to split a string by three consecutive newlines ( "\\n\\n\\n" ). 我试图将一个字符串拆分三个连续的换行符( "\\n\\n\\n" )。 I was trying str.split('\\n\\n\\n') and it didn't work, but when I changed to str.split("\\n\\n\\n") , it started to work. 我正在尝试str.split('\\n\\n\\n')并且它不起作用,但当我改为str.split("\\n\\n\\n") ,它开始工作。 Could anyone explain to me why such behaviour happens? 谁能向我解释为什么会发生这种行为?

String in single quotes is a raw string. 单引号中的字符串是原始字符串。 So '\\n\\n\\n' is three backslashes and three n , not three line feeds as you expected. 所以'\\n\\n\\n'是三个反斜杠和三个n ,而不是你预期的三个换行符。 Only double quotes string can be escaped correctly. 只有双引号字符串才能正确转义。

puts 'abc\nabc'  # => abc\nabc
puts "abc\nabc"  # => abc
                 #    abc

Single quoted string have the actual/literal contents, eg 单引号字符串具有实际/文字内容,例如

1.9.3-p194 :003 > puts 'Hi\nThere'
Hi\nThere
 => nil 

Whereas double-quoted string 'interpolate' the special characters (\\n) and do the line feed, eg 而双引号字符串'插入'特殊字符(\\ n)并进行换行,例如

1.9.3-p194 :004 > puts "Hi\nThere"
Hi
There
 => nil 
1.9.3-p194 :005 > 

Best practice Recommendations: 最佳实践建议:

  • Choose single quotes over double quotes when possible (use double quotes as needed for interpolation). 尽可能在双引号上选择单引号(根据需要使用双引号进行插值)。
  • When nesting 'Quotes inside "quotes" somewhere' put the double ones inside the single quotes 当嵌套“引用内部”引用“某处”时,将双引号放在单引号内

在单引号字符串文字中,反斜杠不需要加倍

'\n' == '\\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM