Last active
August 29, 2015 14:09
-
-
Save launchkit-codes/7979a35eeb1e5836e390 to your computer and use it in GitHub Desktop.
Ruby Method-Calling Hierarchy Between Modules and Classes
This file contains hidden or 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 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 | |
This file contains hidden or 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 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