Can someone explain to me why "\n".length returns 1 and '\n'.length returns 2?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With