4

Can someone explain to me why "\n".length returns 1 and '\n'.length returns 2?

sawa
  • 165,429
  • 45
  • 277
  • 381
appostolis
  • 2,294
  • 2
  • 13
  • 15
  • 3
    Read this - http://en.wikibooks.org/wiki/Ruby_Programming/Strings ... – Arup Rakshit May 02 '14 at 18:53
  • 1
    I should have thought that actually, how the single and double quotes work in general. I just had in my mind that the double quotes are only for string interpolation and I use single only when I'm 100% sure that my object is a string. – appostolis May 02 '14 at 18:59

2 Answers2

9

Because backslash escape sequences are not processed in single-quoted strings. So "\n" is a newline (which is one character), but '\n' is literally a backslash followed by an 'n' (so two characters). You can see this by asking for each string's individual characters:

irb(main):001:0> "\n".chars  #=> ["\n"]
irb(main):002:0> '\n'.chars  #=> ["\\", "n"]

..or just by printing them out:

irb(main):001:0> puts "a\nb"
a
b
irb(main):002:0> puts 'a\nb'
a\nb
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
4

Double quoted strings in ruby are sensitive to escape sequences. \n is an escape sequence for a "newline" character (ascii 0x0A). However, single quoted strings in ruby do not look for escape sequences, so your second string is a literal backslash character, followed by a literal n.

alexsanford1
  • 3,587
  • 1
  • 19
  • 23