Created
February 12, 2013 19:29
-
-
Save rab/4772609 to your computer and use it in GitHub Desktop.
Experiments with where Module#prepend locates the module in the ancestors chain.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ruby-2.0.0dev] code/ruby $ irb | |
irb2.0.0> module Bar; def who; puts 'bar'; end; end | |
#2.0.0 => nil | |
irb2.0.0> class Baz; def who; puts 'baz'; end; end | |
#2.0.0 => nil | |
irb2.0.0> class Foo < Baz; def who; puts 'foo'; end; end | |
#2.0.0 => nil | |
irb2.0.0> Foo.ancestors | |
#2.0.0 => [Foo, Baz, Object, Kernel, BasicObject] | |
All normal so far... | |
irb2.0.0> module Quux; def who; puts 'quux';end ;end | |
#2.0.0 => nil | |
irb2.0.0> Foo.class_eval { prepend Quux } | |
#2.0.0 => Foo | |
irb2.0.0> Foo.ancestors | |
#2.0.0 => [Quux, Foo, Baz, Object, Kernel, BasicObject] | |
While an include Quux would have placed the module after Foo and before the superclass Baz, prepend puts it at the front of the list. | |
irb2.0.0> Foo.class_eval { include Bar } | |
#2.0.0 => Foo | |
irb2.0.0> Foo.ancestors | |
#2.0.0 => [Quux, Foo, Bar, Baz, Object, Kernel, BasicObject] | |
Here we see that an included module, Bar, does still go there in fact. | |
irb2.0.0> Foo.new.who | |
quux | |
#2.0.0 => nil | |
irb2.0.0> class Kid < Foo; def who; puts 'Kid'; end; end | |
#2.0.0 => nil | |
irb2.0.0> Kid.ancestors | |
#2.0.0 => [Kid, Quux, Foo, Bar, Baz, Object, Kernel, BasicObject] | |
A new subclass has all of its superclass's ancestors. | |
irb2.0.0> module Late; def who; puts 'late'; end; end | |
#2.0.0 => nil | |
irb2.0.0> Foo.class_eval { prepend Late } | |
#2.0.0 => Foo | |
irb2.0.0> Foo.ancestors | |
#2.0.0 => [Late, Quux, Foo, Bar, Baz, Object, Kernel, BasicObject] | |
A second prepend on Foo again places the module at the beginning of its ancestors list. | |
irb2.0.0> Kid.ancestors | |
#2.0.0 => [Kid, Late, Quux, Foo, Bar, Baz, Object, Kernel, BasicObject] | |
And the subclass has a consistent behavior; the superclass's ancestors follow in the list. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment