Robert
Robert

Reputation: 41

Ruby - pass variable to eval method

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"

Upvotes: 1

Views: 9235

Answers (1)

maček
maček

Reputation: 77778

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

Upvotes: 14

Related Questions