Ruby - 将变量传递给eval方法

Rob*_*ert 1 ruby idioms eval metaprogramming function

我有一个引用方法的变量,我用eval关键字调用该方法

a_test = "myvariable"
eval a_test


def myvariable
(...)
end
Run Code Online (Sandbox Code Playgroud)

我想将一个变量传递给方法,例如

def myvariable(var1)
(...)
end
Run Code Online (Sandbox Code Playgroud)

是否有人熟悉任何"成语"的方式来实现这一目标.做点什么

eval a_test "string_test" 
Run Code Online (Sandbox Code Playgroud)

自然会失败,因为解释器将对名为"a_test"的函数进行查找

mač*_*ček 14

这应该适合你

def myvariable(foo)
  return "hello #{foo}"
end
a_test = "myvariable"

eval "puts #{a_test}('world')"

#=> hello world
Run Code Online (Sandbox Code Playgroud)

但是在红宝石中,做这样的事情会更合适

def myvariable(foo)
  return "hello #{foo}"
end
a_test = "myvariable"

puts send(a_test, 'world')

#=> hello world
Run Code Online (Sandbox Code Playgroud)

了解更多 send