How to do “late” string interpolation in Ruby

前端 未结 6 965
再見小時候
再見小時候 2021-01-01 10:55
>> string = \'#{var}\'
=> \"\\#{var}\"

>> proc = Proc.new { |var| string }
=> #

>> proc.call(123)
=> \"\\         


        
6条回答
  •  天命终不由人
    2021-01-01 11:29

    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.

    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"
    

    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.

提交回复
热议问题