如何从字符串插值中转义 #{

发布于 2024-08-02 07:34:51 字数 298 浏览 2 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撩起发的微风 2024-08-09 07:34:51

对于无需手动转义所有潜在插值的定界符,您可以使用单引号样式定界符。它的工作原理如下:

item = <<-'END'
  #{code} stuff
  whatever i want to say #{here}
END

For heredoc without having to hand-escape all your potential interpolations, you can use single-quote-style-heredoc. It works like this:

item = <<-'END'
  #{code} stuff
  whatever i want to say #{here}
END
毁我热情 2024-08-09 07:34:51

我认为反斜杠哈希只是 Ruby 以某种仅限 irb 的方式提供帮助。

>> a,b = 1,2        #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s           #=> 1 #{b}
>> s.size           #=> 6

所以我认为你已经有了正确的答案。

I think the backslash-hash is just Ruby being helpful in some irb-only way.

>> a,b = 1,2        #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s           #=> 1 #{b}
>> s.size           #=> 6

So I think you already have the correct answer.

清晨说晚安 2024-08-09 07:34:51

您可以使用 ' 引号代替。其中包含的任何内容都不会被插值。

您使用转义 # 的解决方案也适用于我。事实上,Ruby 解释器会显示,

=> "\#{anything}"

> puts "\#{anything}"
#{anything}
=> nil

您的字符串完全包含您想要的内容,只有 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 shows

=> "\#{anything}"

but

> puts "\#{anything}"
#{anything}
=> nil

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文