2

Given the various ways of sharing methods in Ruby, and the fact that those methods are themselves objects, what are the underlying mechanics of such sharing? For example, given:

module A
  def alpha; end
end

module B
  include A
end

is it accurate to say that B's alpha instance method is a copy of A's? It appears so:

alpha_a = A.instance_method(:alpha)
alpha_b = B.instance_method(:alpha)

alpha_a == alpha_b
=> false

alpha_a.object_id == alpha_b.object_id
=> false

This makes it look (to me) like alpha_b is a copy of alpha_a that belongs to B. But reading about Ruby's handling of method-lookup/dispatch, it sounds the call traverses the ancestors all the way back to A before finding the method to call. Also, there's this:

alpha_b.owner
=> A

So what exactly is going on? Do alpha_a and alpha_b both "reside" in A, despite the latter having been generated when B included A? Do the underlying mechanics depend on the mode of sharing (include/extend/inherit)?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
ivan
  • 6,032
  • 9
  • 42
  • 65

1 Answers1

3

alpha_a is an object that describes the method alpha on A. It is not the method itself. The method itself, just like a block, is not an object, just like blocks are not objects but can be wrapped in Proc objects. Similarly, alpha_b describes the method alpha on B.

The method itself is the same: it is defined on module A. There is no copying going on.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I thought methods were objects. For example, `m = Array.instance_method(:flatten) #=> # `. `m.is_a? Object #=> true`. Is my reasoning faulty? – Cary Swoveland Nov 25 '15 at 06:05
  • @CarySwoveland: `Method`s and `UnboundMethod`s are objects that describe methods, which are not. The distinction between `Method` and method is important here. – Amadan Nov 25 '15 at 06:06
  • @CarySwoveland: http://stackoverflow.com/questions/2602340/methods-in-ruby-objects-or-not – Amadan Nov 25 '15 at 06:10
  • Thanks. One more for the to-do list. – Cary Swoveland Nov 25 '15 at 06:12
  • @CarySwoveland: I just thought of a good analogy that makes it clear. Are files objects in Ruby? Clearly no - files are not in Ruby, but on the disk. But `File`s are objects (in Ruby) that describe - and allow you to interact with - files (on the disk). A `File` is not a file (clearly); the very same reasoning applies to Ruby methods, even if it is not as obvious.,. – Amadan Nov 26 '15 at 23:40
  • Yes, a great analogy. – Cary Swoveland Nov 27 '15 at 02:24