1

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
asked Nov 24, 2011 at 19:13
2
  • try this eval "#{a_test}('string_test')" Commented Nov 24, 2011 at 19:20
  • Just to make it clean: myvariable in this case is not a variable. Commented Nov 24, 2011 at 20:55

1 Answer 1

14

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.