Ruby Unbound Methods: Is it possible to force bind

2019-04-19 15:02发布

问题:

I would like to know if I could force this to happen

class A
  def bomb ; "bomb" ; end
end

class B ; end

bomb = A.instance_method(:bomb)

b = B.new
bomb.bind(b)

currently it throws the error TypeError: bind argument must be an instance of A

I find this very limiting concerning what I can do with these unbound methods, the possibilities are a bit limiting. In cases like these (and I'm not referring only to idempotent functions) it would make sense right? And an execution error would have sufficed, In case I would be handling variables from A which are not replicated in B. I'd really like to know how to force this bind.

回答1:

You cant bind instance of a class with the method of another class. Unless instance is an object of this class, or its sub-classes.

And this is obvious too, the detail of one class cant be transferred to instance of other class. It can be bound with only that instance which is authorized to carry that information that is, the instance of that class or its sub-class.

Hence ruby also maintains encapsulation by not binding method of particular class to instance of another class.



回答2:

Method and UnboundMethod types expect that the bind target must be subclass of the original class where you have referenced the method. Converting the method to proc gets rid of the subclass constraint, but only Method has to_proc method implemented.

class A
  def bomb ; "bomb" ; end
end

class B ; end

bomb = A.new.method(:bomb)

B.send(:define_method, :bomb_in_b, &bomb) #converting to proc

b = B.new
puts b.bomb_in_b

Tested in Ruby 2.2.3