Paul Battley
4/22/2005 9:25:00 AM
On 22/04/05, Neville Burnell <Neville.Burnell@bmsoft.com.au> 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.