Why is this control character not working in Ruby?

the code:

file.write 'objectclass: groupOfUniqueNames\n' 

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

+7
ruby file-io escaping
source share
3 answers

Single quotes in Ruby are more "literal" than double-quoted strings; variables are not evaluated, and most escape characters do not 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" 
+7
source share

The only two escape sequences allowed in a single quote string are \' (for one quote) and \\ (for one backslash). If you want to use other escape sequences, such as \n (for a new line), you must use a double-quoted string.

So this will work:

 file.write "objectclass: groupOfUniqueNames\n" 

Although I personally would just use puts here, which already adds a new line:

 file.puts 'objectclass: groupOfUniqueNames' 
+4
source share

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

+3
source share

All Articles