Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of "\n" and '\n' [duplicate]

Tags:

ruby

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

like image 275
appostolis Avatar asked Dec 12 '22 06:12

appostolis


1 Answers

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
like image 180
Mark Reed Avatar answered Mar 19 '23 03:03

Mark Reed