Ruby Unbound Methods: Is it possible to force bind to instances of other classes?

帅比萌擦擦* 提交于 2019-12-05 01:36:47

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!