diedthreetimes
diedthreetimes

Reputation: 4115

Oddity with "\n" vs '\n'

I have been away from ruby for awhile and I noticed something very strange (at least to me) in 1.9.3. Perhaps someone can explain it to me.

I was trying to split a string into lines so i did string.split('\n'), but this was giving me hell.

Eventually I tracked down the problem to using single quotes instead of double quotes. That is string.split("\n")

In the process of tracking this down I noticed a few things

  1. '\n'.ord == 92
  2. "\n".ord == 10
  3. '\'.ord is not valid ruby
  4. '\\'.ord == 92

The only theory I have is that the single quotes cause ruby to not parse the string and thus treat \n as two characters. However, if this is the case why does '\' not pass the processor?

Am I missing something? Why doesn't split convert the string to the correct ascii?

P.S. Here is some test code to illustrate my point

"asdf\nasdf".split('\n').size #=> 1
"asdf\nasdf".split("\n").size #=> 2

Upvotes: 2

Views: 388

Answers (3)

nwmcsween
nwmcsween

Reputation: 361

Double quotes do interpretation / processing within the string, thus "\n" is a newline while '\n' is a \ and an n.

Upvotes: 1

ashastral
ashastral

Reputation: 2848

In addition to xdazz's information, '\'.ord is syntactically incorrect because the backslash escapes the following single quote. Use '\\'.ord for that purpose instead.

Upvotes: 3

xdazz
xdazz

Reputation: 160833

'\n' is a string contain 2 char \ and n.

"\n" is a string contain 1 char, the new line char (LF) with ascii code 10.

When you use double quote, \ is used to escape special chars.

Upvotes: 6

Related Questions