我有一个引用方法的变量,我用 eval 关键字调用该方法
a_test = "myvariable"
eval a_test
def myvariable
(...)
end
我想传递一个变量给方法,例如
def myvariable(var1)
(...)
end
是否有人熟悉完成此操作的任何“成语”方式。做类似的事情
eval a_test "string_test"
自然会失败,因为解释器将查找名为“a_test”的函数
最佳答案
这应该适合你
def myvariable(foo)
return "hello #{foo}"
end
a_test = "myvariable"
eval "puts #{a_test}('world')"
#=> hello world
虽然在 ruby 中,做这样的事情会更合适
def myvariable(foo)
return "hello #{foo}"
end
a_test = "myvariable"
puts send(a_test, 'world')
#=> hello world
阅读更多关于 send
的信息
关于Ruby - 将变量传递给 eval 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8261588/