Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created October 30, 2011 22:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancejpollard/1326526 to your computer and use it in GitHub Desktop.
Save lancejpollard/1326526 to your computer and use it in GitHub Desktop.
How modules are added to the inheritance chain in Ruby
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