Zombies
Zombies

Reputation: 25872

Why doesn't this escape character actually work in Ruby?

code:

file.write 'objectclass: groupOfUniqueNames\n'

Oddly enough, the \n is actually being printed... What is wrong here?

Upvotes: 8

Views: 1148

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

The only two escape sequences allowed in a single quoted string are \' (for a single quote) and \\ (for a single backslash). If you want to use other escape sequences, like \n (for newline), you have to use a double quoted string.

So, this will work:

file.write "objectclass: groupOfUniqueNames\n"

Although I personally would simply use puts here, which already adds a newline:

file.puts 'objectclass: groupOfUniqueNames'

Upvotes: 4

user229044
user229044

Reputation: 239301

Single quoted strings in Ruby are more 'literal' than double quoted strings; variables are not evaluated, and most escape characters don't work, with the exception of \\ and \' to include literal backslashes and single quotes respectively.

Double quotes are what you want:

file.write "objectclass: groupOfUniqueNames\n"

Upvotes: 7

sepp2k
sepp2k

Reputation: 370172

You're using single quotes. The only escape sequences allowed in single quotes are \\ for \ and \' for '. Use double quotes and \n will work as expected.

Upvotes: 3

Related Questions