Backslash breaks string interpolation in ruby [closed]

白昼怎懂夜的黑 提交于 2019-12-08 12:02:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!