Last active
December 24, 2015 16:09
-
-
Save odlp/6825538 to your computer and use it in GitHub Desktop.
Ruby - examples of cascading & namespacing
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
# EXAMPLE 1: Cascade | |
# Two modules happen to have the same method ('say'). | |
# If we include the Shouting module last, the Shouting 'say' method overwrites the Talkable 'say' method. | |
module Talkable | |
def say (str) | |
puts str | |
end | |
end | |
module Shouting | |
def say (str) | |
puts str.upcase | |
end | |
end | |
class Person | |
include Talkable | |
include Shouting | |
end | |
bob = Person.new | |
bob.say("hello") # => 'HELLO' is capitalized because Shouting's 'say' method has precedence over Talking's 'say' method |
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
# EXAMPLE2: Including part of a module using namespaces | |
module Greetings | |
module English | |
def hello | |
puts "Hello" | |
end | |
end | |
module French | |
def hello | |
puts "Bonjour" | |
end | |
end | |
end | |
class Person | |
include Greetings::English # getting just the English module within Greetings module. | |
end | |
bob = Person.new | |
bob.hello # => "Hello" rather than "Bonjour". | |
# Didn't include French module from Greetings, so it's not overwriting the English 'hello' method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment