如果我有字符串"this is a \#test"
并将其放入Python shell,我会回到'this is a \\#test'
,这是我正在寻找的行为。但是如果我把它放到Ruby shell中,我会回到"this is a #test"
,但没有迹象表明存在反斜杠。如何使Ruby字符串表现得像Python,也就是说,不会自动转义我的#符号?
答案 0 :(得分:2)
当您不希望解释转义序列时使用单引号。
[1] pry(main)> 'this is a \#test'
=> "this is a \\#test"
单引号也不会进行字符串插值,所以如果你需要两个,你可以手动转义斜杠:
[1] pry(main)> t = "test" ; "this is a \\##{t}"
=> "this is a \\#test"
答案 1 :(得分:2)
只使用单引号而不是双引号:
'this is a \#test'
将包含反斜杠。在Ruby中,只有"
个字符串可以进行替换和转义。 '
个字符串仅从\\
转到\