“迟到"怎么办?Ruby 中的字符串插值 [英] How to do "late" string interpolation in Ruby
问题描述
>> string = '#{var}'
=> "\#{var}"
>> proc = Proc.new { |var| string }
=> #<Proc:0xb717a8c4@(pry):6>
>> proc.call(123)
=> "\#{var}"
不是我想要的.string
周围的双引号导致明显的未定义的局部变量
.
Not really what I want. Double quotes around string
result in the obvious undefined local variable
.
推荐答案
虽然这是可能的,但如果不使用 eval
,它不会按照您的预期工作,通常这是一个坏主意如果有替代方案.好消息是您有多种选择.
Although this is possible, it's not going to work how you intend here without having to use eval
, and generally that's a bad idea if there's an alternative. The good news is you have several options.
最直接的是使用 sprintf
格式,使用 String#%
方法更容易:
The most straightforward is to use sprintf
formatting which is made even easier with the String#%
method:
string = '%s'
proc = Proc.new { |var| string % var }
proc.call(123)
# => "123"
这是一种非常可靠的方法,因为任何支持 .to_s
方法的方法都可以工作,并且如果它包含可执行代码,则不会导致 Universe 内爆.
This is a really reliable method as anything that supports the .to_s
method will work and won't cause the universe to implode if it contains executable code.
这篇关于“迟到"怎么办?Ruby 中的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!