Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

methods

ruby

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?

like image 884
Sir Robert Avatar asked May 26 '11 21:05

Sir Robert


1 Answers

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"
like image 136
tokland Avatar answered Nov 17 '22 07:11

tokland