Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
Zombies Avatar asked Feb 03 '10 19:02

Zombies


People also ask

How do you escape a character in Ruby?

When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.

How do you escape characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

How do I escape a character in a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.


1 Answers

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"
like image 134
meagar Avatar answered Sep 24 '22 17:09

meagar