Felipe
Felipe

Reputation: 11897

Single quotes vs double quotes

I am trying to split a string by three consecutive newlines ("\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. Could anyone explain to me why such behaviour happens?

Upvotes: 2

Views: 722

Answers (3)

Michael Durrant
Michael Durrant

Reputation: 96614

Single quoted string have the actual/literal contents, e.g.

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, e.g.

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

Upvotes: 5

megayu
megayu

Reputation: 161

In single-quoted string literals, backslashes need not be doubled

'\n' == '\\n'

Upvotes: 0

halfelf
halfelf

Reputation: 10107

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. Only double quotes string can be escaped correctly.

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

Upvotes: 8

Related Questions