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)?

2
  • You're generating the unbound method by calling instance_method. There's no "copy" of the module method itself; it resides in A. Nov 25, 2015 at 5:48
  • Note that B.ancestors #=> [B, A], A.ancestors #=> [A]. . Nov 25, 2015 at 6:15

1 Answer 1

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.

6
  • I thought methods were objects. For example, m = Array.instance_method(:flatten) #=> #<UnboundMethod: Array#flatten> . m.is_a? Object #=> true. Is my reasoning faulty? Nov 25, 2015 at 6:05
  • @CarySwoveland: Methods and UnboundMethods are objects that describe methods, which are not. The distinction between Method and method is important here.
    – Amadan
    Nov 25, 2015 at 6:06
  • @CarySwoveland: stackoverflow.com/questions/2602340/…
    – Amadan
    Nov 25, 2015 at 6:10
  • Thanks. One more for the to-do list. Nov 25, 2015 at 6: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 Files 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, 2015 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.