2

I'm trying to call a method of an object foo as if it was an method of object bar. I tried two approaches:

1. unbind and bind - fails because of different classes

class Foo
  def initialize
    @name = "John"
  end
end

class Bar
  def out
    puts @name
  end
end

foo = Foo.new
bar = Bar.new

m = bar.method :out
foo.instance_eval m.unbind.bind(foo)

2. instance_eval on proc made from method

This fails on the fact that instance_eval passes a reciever as an additional argument instead of the real reciever (afaik)

class Foo
  def initialize
    @name = "John"
  end
end

class Bar
  def out
    puts @name
  end
end

foo = Foo.new
bar = Bar.new

m = bar.method :out
proc = m.to_proc
foo.instance_eval &proc

It says: in `out': wrong number of arguments (1 for 0) (ArgumentError) in the stacktrace.

However when I use this instead of the last line it works fine:

foo.instance_eval {
  puts @name
}

1 Answer 1

2

The problem is that #instance_eval sends to the block a parameter that is the object it self. So you can do it:

# ...
class Bar
  def out(foo_object)
    [@name, foo_object, self]
  end
end
# ...
m = bar.method :out
foo.instance_eval &m    # => ["John", #<Foo:0x1c11b10>, #<Bar:0x1bb2470>]

The argument is place where the method is called and self is from here the method is. I don't know how to call the method without parsing this extra argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.