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"

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.