Lengths "\ n" and "\ n"

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

+4
source share
2 answers

Because backslash escape sequences are not processed on single-quoted strings. So, "\n"this is a newline character (this is one character), but '\n'is literally a backslash followed by an "n" (so there are two characters). You can see this by querying each line of individual characters:

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

.. or just by printing them:

irb(main):001:0> puts "a\nb"
a
b
irb(main):002:0> puts 'a\nb'
a\nb
+9
source

escape-.\n - escape- " " (ascii 0x0A). escape-, , n.

+4

Source: https://habr.com/ru/post/1539046/


All Articles