I have a variable which reference a method, I call the method with the eval keyword
a_test = "myvariable"
eval a_test
def myvariable
(...)
end
I would like to pass a variable to method, such as
def myvariable(var1)
(...)
end
Is anyone familiar with any "idiom" way of accomplishing this. Doing something like
eval a_test "string_test"
will naturally fail since a lookup will be done by the interpreter for a function called "a_test"
KL-7
47.9k10 gold badges92 silver badges75 bronze badges
1 Answer 1
This should work for you
def myvariable(foo)
return "hello #{foo}"
end
a_test = "myvariable"
eval "puts #{a_test}('world')"
#=> hello world
In ruby though, it would be more appropriate to do something like this
def myvariable(foo)
return "hello #{foo}"
end
a_test = "myvariable"
puts send(a_test, 'world')
#=> hello world
Read more about send
Rimian
38.6k17 gold badges126 silver badges119 bronze badges
answered Nov 24, 2011 at 19:36
Comments
Explore related questions
See similar questions with these tags.
lang-rb
eval "#{a_test}('string_test')"
myvariable
in this case is not a variable.