Hi all,
I have a situation where I would like to create a string and
interpolate it later (sample code below). The string will be
interpolated while iterating through a potentially long list of
values. To do this I have set up the string as
astring=%q{%{somthing #{foo}}}
and am then using
eval (astring)
to cause the interpolation to happen.
Why? Well one of the variables I want is a block variable and out of
scope outside the block.
Another of the variables that is being interpolated is entered by the
user who I must assume could be malicious. I tried $SAFE=1 and then
back to 0 after the iteration, but it caused an error with 'require'.
Well enough talk; how safe is the following code? Assuming that the
input was passed in from the web rather than a gets. Also, is there a
better way of doing something like this? Thanks in advance for your
input. -Jamal
···
=========================================
class Foozle
def foo
# a hash to iterate through
ahash={ :a => 'This', :b => 'That', :c => 'The other'}
# get some value from user
print 'value:'
user_input=gets.chomp
# our string to interpolate
output=%q{%{#{v} asks, "Is user input '#{user_input}' safe for
any user input when $SAFE==0?"\n}}
# ...and pow!
ahash.each { | k, v | puts eval(output) }
end
end
inst=Foozle.new
inst.foo