如何在变量中获取实例方法?例如:
class Foo
def bar
puts "bar"
end
end
我希望能够操作“bar”实例方法(例如,传递它)。我该怎么做?
我知道我可以得到类常量
foo_class = Kernel.const_get("Foo")
有什么类似的方法可以得到 Foo#bar
吗?
最佳答案
看来你需要一个 UnboundMethod :
class Foo
def initialize(value)
@value = value
end
def bar
@value
end
end
unbound_bar = Foo.instance_method(:bar)
p unbound_bar.bind(Foo.new("hello")).call
#=> "hello"
关于ruby - 如何在 ruby 中获取绑定(bind)到变量的实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145007/