简体   繁体   English

如何将字符串eval / constantize到方法,然后将参数传递给它

[英]how to eval / constantize a string to a method, then pass arguments to it

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: 我如何评估或限制s,并将参数传递给它,例如我的最终结果将相当于:

foo_bar_path(@myvar, @foobar)

I was trying eval(s).send but that doesn't seem to work. 我正在尝试eval(s).send但这似乎不起作用。 And constantize seems to only work on Classes? constantize似乎只适用于类?

You would just use the send method (or public_send depending on your needs) on the appropriate object: 您只需在适当的对象上使用send方法 (或public_send具体取决于您的需要):

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. 文档说“符号”,但send同样乐于在字符串中获取方法名称。

Another way to go about this sort of this sort of thing (better for OpenStruct): 另一种解决此类问题的方法(对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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM