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

时间:2022-12-25 22:27:44

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 #{.

我有一个heredoc,我使用#{}来插入一些其他字符串,但是有一个实例,我也想在我的heredoc中编写实际的文本#{some_ruby_stuff},而不进行插值。有没有办法逃脱#{。

I've tried "\", but no luck. Although it escapes the #{}, it also includes the "\":

我试过“\”,但没有运气。虽然它逃脱#{},但它也包含“\”:

>> <<-END
 #{RAILS_ENV} \#{RAILS_ENV} 
END
=> " development \#{RAILS_ENV}\n"

3 个解决方案

#1


17  

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

我认为反斜杠哈希只是Ruby在一些irb-only方式中有用。

>> 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.

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

#2


18  

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

对于heredoc而不必手动转义所有可能的插值,您可以使用单引号样式的heredoc。它的工作原理如下:

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

#3


4  

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

逃避#的解决方案也适用于我。事实上Ruby解释器显示

=> "\#{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.

您的字符串包含您想要的内容,只有p方法使用转义字符显示它。实际上,p方法向您展示了如何编写字符串以获得由其参数表示的完全对象。

#1


17  

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

我认为反斜杠哈希只是Ruby在一些irb-only方式中有用。

>> 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.

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

#2


18  

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

对于heredoc而不必手动转义所有可能的插值,您可以使用单引号样式的heredoc。它的工作原理如下:

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

#3


4  

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

逃避#的解决方案也适用于我。事实上Ruby解释器显示

=> "\#{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.

您的字符串包含您想要的内容,只有p方法使用转义字符显示它。实际上,p方法向您展示了如何编写字符串以获得由其参数表示的完全对象。