如何评估/常量化字符串到方法,然后将参数传递给它

发布于 2024-12-07 15:47:20 字数 226 浏览 4 评论 0原文

给出:

s = "foo_bar_path"

我如何评估或常量化 s,并将参数传递给它,例如我的最终结果相当于:

foo_bar_path(@myvar, @foobar)

我正在尝试 eval(s).send 但这似乎并不工作。而且 Constantize 似乎只适用于类?

Given:

s = "foo_bar_path"

How can I eval or constantize s, and pass arguments to it, such as my final result would be the equivalent of:

foo_bar_path(@myvar, @foobar)

I was trying eval(s).send but that doesn't seem to work. And constantize seems to only work on Classes?

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

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

发布评论

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

评论(2

南薇 2024-12-14 15:47:20

您只需使用 send 方法 (或 public_send根据您的需要)在适当的对象上:

some_object.send(s, @myvar, @foobar)

或者如果您想对自己调用方法:

self.send(s, @myvar, @foobar)

文档中说“符号”,但 send 也很乐意获取字符串中的方法名称。

You would just use the send method (or public_send depending on your needs) on the appropriate object:

some_object.send(s, @myvar, @foobar)

or if you want to call a method on yourself:

self.send(s, @myvar, @foobar)

The documentation says "symbol" but send is just as happy to get the method name in a string.

临风闻羌笛 2024-12-14 15:47:20

另一种处理此类事情的方法(对于 OpenStruct 更好):

#for more in this domain, see the Ruby core API for the Object class
class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
m = k.method(:hello)
m.call   #=> "Hello, @iv = 99"

Another way to go about this sort of this sort of thing (better for OpenStruct):

#for more in this domain, see the Ruby core API for the Object class
class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
m = k.method(:hello)
m.call   #=> "Hello, @iv = 99"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文