反斜杠打破了ruby中的字符串插值
我想最后得到字符串"/a_setting/c\blah = something"
,其中属性被评估为其值:blah。 但是,我看到以下行为,其中前面的反斜杠似乎停止了对变量的评估:
attribute = "blah"
"/a_setting/c\#{attribute} = something"
=> "/a_setting/c\#{attribute} = something"
"/a_setting/c\ #{attribute} = something"
=> "/a_setting/c blah = something"
获取所需的字符串:
"/a_setting/c\\#{attribute} = something"
你需要通过反斜杠来逃避反斜杠。
- 当您执行
"\#"
,"#"
被转义,并且不会被解释为插值元素,而是作为逐字"#"
,在检查中,在{...}
前面显示为"\#"
避免插值歧义。 - 当你执行
"\ "
," "
被(冗余地)转义,并被解释为逐字" "
。
我不明白你指的是什么。
但是如果你试图在字符串中对你的属性进行评估,那么这可能是你想要的
"/a_setting/c\\#{attribute} = something"
因为
"/a_setting/c\#{attribute} = something"
你正在通过添加转义字符#{}
来逃避评估
因此,解释器将评估#{}
而不是表达式。
当您在另一个\
之前添加另一个\
,下一个\将被转义并作为普通字符进行评估。
"\#{attribute}" #:=> "\{attribute} "\\#{attribute}" #;=> "\blah"