tags:

views:

96

answers:

3

Hi,

I am trying to pass a variable to a dynamically declared method like:

eval(def test(name)
 puts name
end
test 'joe')

but it does not work.

Is there a way to do this?

+9  A: 

eval expects a string. The following should work fine:

eval "def test(name)
  puts name
end
test 'joe'"
Brian McKenna
Thanks for reminding Brian. It works. Not sure why I missed that.
Nick
A: 

I am a little confused on what you are trying to do. If you are trying to define a method with eval that can take a parameter here is the example:

eval "def test(name)
  puts name
end"

test 'joe'

If you want to use eval to define a method that is more dynamic and uses a variable, since as Brian pointed out eval takes a string you would do something like this:

test_name = 'joe'
eval "def test
  puts '#{test_name}'
end"

test
ScottD
Either works, depending on what the OP wants. Clearly he'll be interpolating something somewhere, since, otherwise, why use `eval`?
Matchu
I was trying to read a method stored in the database and then execute it with parameters.
Nick
Do you know that the parameters are and their order before you read it in? If so then using eval with the string should work.
ScottD
+6  A: 

If you want to declare a method dynamically then a better way to do that is to use define_method instead of eval, like so

define_method(:test) do |name|
  name
end

test 'joe'
#=> joe

Don't use eval unless it is absolutely necessary and you are 120% sure that it is safe. Even if you are 120% sure that it is safe, still try to look for other options and if you find one then use that instead of eval.

nas