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

江枫思渺然 提交于 2019-12-10 02:02:24

问题


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



来源:https://stackoverflow.com/questions/13234284/ruby-unbound-methods-is-it-possible-to-force-bind-to-instances-of-other-classes

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