Nick
Nick

Reputation: 271

Can I pass variables to eval?

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?

Upvotes: 5

Views: 1799

Answers (3)

nas
nas

Reputation: 3696

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.

Upvotes: 7

scottd
scottd

Reputation: 7474

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

Upvotes: 0

Brian McKenna
Brian McKenna

Reputation: 46218

eval expects a string. The following should work fine:

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

Upvotes: 11

Related Questions