Skip to content

Instantly share code, notes, and snippets.

@launchkit-codes
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save launchkit-codes/7979a35eeb1e5836e390 to your computer and use it in GitHub Desktop.

Select an option

Save launchkit-codes/7979a35eeb1e5836e390 to your computer and use it in GitHub Desktop.
Ruby Method-Calling Hierarchy Between Modules and Classes
# Ruby Method-Calling Hierarchy.
#
# When a method is called Ruby :
#
# 1 - searches the method in class.
#
# 2- searches the method in each included modules
# from the last one to the first one.
#
# Study Case:
#
# 1- A Cat is Wild but his Feline side is more visible.
#
# 2- A Tiger is a Feline but his Wild side is more visible.
#
# 3- A Bobcat is Wild and is a Feline.. BUT a Bobcat is a Bobcat.
module Wild
def roar
puts 'Wild: arrrrgh !'
end
end
module Feline
def roar
puts 'Feline: miaou !'
end
end
class Cat
include Wild
include Feline
end
class Tiger
include Feline
include Wild
end
class Bobcat
include Feline
include Wild
def roar
puts 'Bobcat: ... !'
end
end
Cat.new.roar
Tiger.new.roar
Bobcat.new.roar
$> ruby modules_and_classes.rb
Feline: miaou !
Wild: arrrrgh !
Bobcat: ... !
$>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment