Is a line feed a string?


#1

https://play.crystal-lang.org/#/r/64ml

test = "hello\nhi"

pp test

pp test.includes? "n"

As we can see, the line feed \n is printed on line 3, we can confirm that because pp's output is:
"hello\n" + "hi" (see the +)

however, in the docs, it says:
https://crystal-lang.org/api/0.27.0/String.html#includes%3F(search%3AChar|String)-instance-method

Returns true if the string contains search .

I asked gitter about this last week or so, but my head still explodes when I see this code.

Do the combination of letters \ and n get converted into a line feed when read, making the n disappear? Thus returning false? But, at the same time, the letters \ and n are inside a string :thinking:

edit: I think my first hypothesis is correct, because if you look here https://play.crystal-lang.org/#/r/64mq, it returns true. Because \z isn’t a carriage, line feed, etc?


#2

Hi!

Make sure to read the Char docs: https://crystal-lang.org/reference/syntax_and_semantics/literals/char.html

\n inside a string literal is an escape sequence denoting a newline. It’s not “n” nor “”, it’s a newline. It’s the same as writing a newline inside a string literal, only that \n is visually easier to notice and talk about. It’s also what gets printed when you use inspect (p and pp use inspect) but when you use puts you’ll see a newline printed.

Escape sequences like these exist in mostly all programming languages, dating back to C and probably even before that.


#3

“Escape sequence” is what triggered my brain to understand what’s happening. I get it now :P. Thanks!