开发者

How do I get an instance method bound to a variable in ruby?

开发者 https://www.devze.com 2023-03-08 12:16 出处:网络
How can I get an instance method in a variable?For example: class Foo def bar puts \"bar\" end end I want to be able to manipulate the \"bar\" instance method (for example, to pass it around).How c

How can I get an instance method in a variable? For example:

class Foo
  def bar
    puts "bar"
  end
end

I want to be able to manipulate the "bar" instance method (for example, to pass it around). How can I do it?

I know that I can get the class constant with

foo_class = Kernel.const_get("Foo")

Is there anything 开发者_运维问答similar I can do to get Foo#bar?


It seems you need an 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"


method(:bar) in the method scope. You can call that one, it's still bound to self.


See the Ruby documentation for UnboundMethod.

0

精彩评论

暂无评论...
验证码 换一张
取 消