Search code examples
rubystringescapingquotesdouble-quotes

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?


Solution

  • 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