From: Paul Battley Date: 2005-04-22T18:25:00+09:00 Subject: Re: Clean way to dynamically expand string with "#{expression}"? On 22/04/05, Neville Burnell wrote: > How about: > > irb(main):001:0> n = 1 > => 1 > irb(main):002:0> s = 'n = #{n}' > => "n = \#{n}" > irb(main):003:0> puts eval('"' + s + '"') > n = 1 > => nil If you use eval, you should be careful to escape both backslashes and quotes in the string. You can also define a method to handle it: def interpolate(str, bnd) return eval('"' << str.gsub(/\\/, "\\\\\\\\").gsub(/"/, "\\\\\"") << '"', bnd) end n = 3 interpolate('n = #{n}', binding) # => "n = 3" interpolate('\n = #{n}', binding) # => "\\n = 3" interpolate('\"; `ls`; "n = #{n}', binding) # => "\\\"; `ls`; \"n = 3" # OK so far... interpolate('n = #{`ls`}', binding) # => "n = [long directory listing]" As you can see, there are risks inherent in using eval. This can be mitigated against by using $SAFE and tainting, and thereby avoiding eval'ing untrusted input. Paul.