Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 382
ChuckE Avatar asked Nov 05 '12 14:11

ChuckE


2 Answers

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.

like image 142
Akshay Vishnoi Avatar answered Sep 18 '22 20:09

Akshay Vishnoi


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

like image 43
karatedog Avatar answered Sep 19 '22 20:09

karatedog