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

2

14

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.

Gaw answered 5/11, 2012 at 14:37 Comment(3)
Something interesting that is possible: Object.instance_method(:to_s).bind("hello world").call #=> "#<String:0x0000000195e1f0>". I don't think it's possible to force the binding in your example though.Faxon
Yes, that is because String inherits from Object, and you can bind superclass instance methods to its children class instances. An example: class A ; def t ; "A" ; end ; end ; class B < A ; def t ; "B" ; end ; end ; A.instance_method(:t).bind(B.new).call . But still, I would like to make the method a function and then a proc and then call it wherever I wanted. But maybe I'm a dreamer :)Gaw
if A would have been a module, then it is possible in ruby 2Propel
H
2

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.

Hone answered 5/11, 2012 at 19:5 Comment(0)
X
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

Xebec answered 2/11, 2015 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.