开发者

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开发者_StackOverflow a way to do this?


eval expects a string. The following should work fine:

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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜