views:

184

answers:

3

code:

file.write 'objectclass: groupOfUniqueNames\n'

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

+2  A: 

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.

sepp2k
Actually, not even `\\` works. (Which BTW means that you cannot have a single quoted string that ends with an odd number of backslashes.)
Jörg W Mittag
Of course it works: `'\\' == "\\" #=> true`
sepp2k
@Jörg W Mittag: Note that `'\\'.size == 1`, which is an odd number.
sepp2k
Yes, of course. How stupid of me. I typed `'\\'` into IRB and got back `"\\"` and I thought: hey, I put two backslashes in and two came out, therefore they weren't escaped. But, of course, they are printed back in escaped form. Duh!
Jörg W Mittag
+7  A: 

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"
meagar
So why would I really ever want to use single quote strings? Is it just short hand to avoid escaping characters?
Zombies
It can also be useful if you don't want to interpolate. For example: `'Interpolation looks like this: #{@variable}'`, which is printed literally, as opposed to `"The value of @foo is #{@foo}"`, wherein `@foo` is evaluated and inserted.
James A. Rosen
@Zombies Single quoted string require less work on Ruby's side. They're a little faster to use when you know you're not going to need things like variable interpolation.
meagar
+4  A: 

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'
Jörg W Mittag