Ruby - 将变量传递给 eval 方法

发布于 2024-12-17 21:37:38 字数 330 浏览 8 评论 0原文

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

a_test = "myvariable"
eval a_test


def myvariable
(...)
end

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

def myvariable(var1)
(...)
end

是否有人熟悉实现此目的的任何“习惯用法”方式。做类似的事情

eval a_test "string_test" 

自然会失败,因为解释器将查找名为“a_test”的函数

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救赎№ 2024-12-24 21:37:38

这应该对你有用

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

阅读更多关于 发送

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文