开发者

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

开发者 https://www.devze.com 2022-12-18 20:15 出处:网络
code: file.write \'objectclass: groupOfUnique开发者_运维知识库Names\\n\' Oddly enough, the \\n is actually being printed... What is wrong here?Single quoted strings in Ruby are more \'literal\' tha

code:

file.write 'objectclass: groupOfUnique开发者_运维知识库Names\n'

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


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"


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'


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号