如何在ruby中获取绑定到变量的实例方法?
发布时间:2020-12-17 03:27:36 所属栏目:百科 来源:网络整理
导读:如何在变量中获取实例方法?例如: class Foo def bar puts "bar" endend 我希望能够操纵“bar”实例方法(例如,传递它).我该怎么做? 我知道我可以让班级保持不变 foo_class = Kernel.const_get("Foo") 有什么类似的东西可以做Foo #bar吗? 解决方法 看来你
如何在变量中获取实例方法?例如:
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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |