Created
October 30, 2011 22:13
-
-
Save lancejpollard/1326526 to your computer and use it in GitHub Desktop.
How modules are added to the inheritance chain in Ruby
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
module ModuleA | |
def method | |
puts "method called from ModuleA" | |
end | |
end | |
module ModuleB | |
def method | |
puts "method called from ModuleB" | |
super | |
end | |
end | |
class Parent | |
include ModuleA | |
def method | |
puts "method called from Parent" | |
super | |
end | |
end | |
class Child < Parent | |
include ModuleB | |
def method | |
puts "method called from Child" | |
super | |
end | |
end | |
Child.new.method | |
#=> method called from Child | |
#=> method called from ModuleB | |
#=> method called from Parent | |
#=> method called from ModuleA | |
puts ModuleA.ancestors.inspect | |
puts ModuleB.ancestors.inspect | |
puts Parent.ancestors.inspect | |
puts Child.ancestors.inspect | |
#=> [ModuleA] | |
#=> [ModuleB] | |
#=> [Parent, ModuleA, Object, Kernel] | |
#=> [Child, ModuleB, Parent, ModuleA, Object, Kernel] | |
Child.ancestors.each do |ancestor| | |
puts ancestor.ancestors.inspect | |
end | |
#=> [Child, ModuleB, Parent, ModuleA, Object, Kernel] | |
#=> [ModuleB] | |
#=> [Parent, ModuleA, Object, Kernel] | |
#=> [ModuleA] | |
#=> [Object, Kernel] | |
#=> [Kernel] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment