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:
foo_bar_path(@myvar, @foobar)
I was trying eval(s).send
but that doesn't seem to work. And const开发者_如何学编程antize seems to only work on Classes?
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.
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"
精彩评论