开发者

Use method in different context, instance_eval adds unwanted argument

开发者 https://www.devze.com 2023-04-10 05:01 出处:网络
I\'m trying to call a method of an object foo as if it was an method of object bar. I tried two approaches:

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) (Argument开发者_运维百科Error) in the stacktrace.

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

foo.instance_eval {
  puts @name
}


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.

0

精彩评论

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

关注公众号