Reputation: 11897
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
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:
Upvotes: 5
Reputation: 161
In single-quoted string literals, backslashes need not be doubled
'\n' == '\\n'
Upvotes: 0
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