问题
I'd like to end up with the string "/a_setting/c\blah = something" where attribute gets evaluated to its value: blah. However, I'm seeing the following behavior where the preceding backslash seems to stop the evaluation of the variable:
attribute = "blah"
"/a_setting/c\#{attribute} = something"
=> "/a_setting/c\#{attribute} = something"
"/a_setting/c\ #{attribute} = something"
=> "/a_setting/c blah = something"
回答1:
To get the string you want:
"/a_setting/c\\#{attribute} = something"
You need to escape the backslash by backslash.
- When you do
"\#", the"#"is escaped, and is interpreted not as an interpolation element, but as the verbatim"#", which in inspection, appears as"\#"in front of{...}to avoid ambiguity with interpolation. - When you do
"\ ", the" "is (redundantly) escaped, and is interpreted as the verbatim" ".
回答2:
I don't understand what you are pointing at.
But if you are trying to have your attributed evaluated in the string, probably this is what you want
"/a_setting/c\\#{attribute} = something"
coz by
"/a_setting/c\#{attribute} = something"
you are escaping the evaluation by #{} by adding the escape character \
So interpreter will evaluate #{} rather as an expression.
When you add another \ before the other \, the next \ is escaped and evaluated as a normal character.
"\#{attribute}" #:=> "\{attribute}
"\\#{attribute}" #;=> "\blah"
来源:https://stackoverflow.com/questions/17650832/backslash-breaks-string-interpolation-in-ruby