In Ruby, can you perform string interpolation on data read from a file?

前端 未结 8 1846
抹茶落季
抹茶落季 2020-12-10 10:37

In Ruby you can reference variables inside strings and they are interpolated at runtime.

For example if you declare a variable foo equals \"Ted\

8条回答
  •  悲&欢浪女
    2020-12-10 10:53

    Might as well throw my own solution into the mix.

    irb(main):001:0> str = '#{13*3} Music'
    => "\#{13*3} Music"
    irb(main):002:0> str.gsub(/\#\{(.*?)\}/) { |match| eval($1) }
    => "39 Music"
    

    The weakness is that the expression you want to evaluate may have further { } in it, so the regex should probably be improved.

提交回复
热议问题