如何从字符串插值中转义 #{
我有一个heredoc,其中使用 #{}
来插入一些其他字符串,但有一个实例,我还想在其中写入实际文本 #{some_ruby_stuff}
我的定理,没有被插值。有没有办法逃脱#{.
我尝试过“\”,但没有成功。虽然它转义了 #{}
,但它还包含“\”:
>> <<-END
#{RAILS_ENV} \#{RAILS_ENV}
END
=> " development \#{RAILS_ENV}\n"
I have a heredoc where I am using #{}
to interpolate some other strings, but there is an instance where I also want to write the actual text #{some_ruby_stuff}
in my heredoc, WITHOUT it being interpolated. Is there a way to escape the #{.
I've tried "\", but no luck. Although it escapes the #{}
, it also includes the "\":
>> <<-END
#{RAILS_ENV} \#{RAILS_ENV}
END
=> " development \#{RAILS_ENV}\n"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于无需手动转义所有潜在插值的定界符,您可以使用单引号样式定界符。它的工作原理如下:
For heredoc without having to hand-escape all your potential interpolations, you can use single-quote-style-heredoc. It works like this:
我认为反斜杠哈希只是 Ruby 以某种仅限 irb 的方式提供帮助。
所以我认为你已经有了正确的答案。
I think the backslash-hash is just Ruby being helpful in some irb-only way.
So I think you already have the correct answer.
您可以使用
'
引号代替。其中包含的任何内容都不会被插值。您使用转义
#
的解决方案也适用于我。事实上,Ruby 解释器会显示,但
您的字符串完全包含您想要的内容,只有
p
方法用转义字符显示它。实际上,p
方法向您展示了应该如何编写字符串才能准确获取其参数所表示的对象。You can use
'
quotes instead. Anything enclosed in them is not being interpolated.Your solution with escaping
#
also works for me. Indeed Ruby interpreter showsbut
Your string includes exactly what you wanted, only
p
method shows it with escape characters. Actually,p
method shows you, how string should be written to get exactly object represented by its parameter.