【发布时间】:2013-10-06 23:23:55
【问题描述】:
如果我有字符串 "this is a \#test" 并将其放入 Python shell,我会返回 'this is a \\#test',这就是我正在寻找的行为。但是,如果我将它放入 Ruby shell 中,我会返回 "this is a #test",但没有任何迹象表明存在反斜杠。如何使 Ruby 字符串表现得像 Python,即不自动转义我的 # 符号?
【问题讨论】:
如果我有字符串 "this is a \#test" 并将其放入 Python shell,我会返回 'this is a \\#test',这就是我正在寻找的行为。但是,如果我将它放入 Ruby shell 中,我会返回 "this is a #test",但没有任何迹象表明存在反斜杠。如何使 Ruby 字符串表现得像 Python,即不自动转义我的 # 符号?
【问题讨论】:
当您不想解释转义序列时使用单引号。
[1] pry(main)> 'this is a \#test'
=> "this is a \\#test"
单引号也不会做字符串插值,所以如果你需要both,你可以手动转义你的斜线:
[1] pry(main)> t = "test" ; "this is a \\##{t}"
=> "this is a \\#test"
【讨论】:
gets 方法的默认行为吗?
gets 方法不会执行任何插值或转义序列。它与引用没有任何关系——它只是从标准输入中读取字符。
只用单引号代替双引号:
'this is a \#test'
将包含反斜杠。在 Ruby 中,只有 " 字符串会进行替换和转义。 ' 字符串只转义 \\ 到 \
【讨论】: