Skip to content

Instantly share code, notes, and snippets.

@odlp
Last active December 24, 2015 16:09
Show Gist options
  • Save odlp/6825538 to your computer and use it in GitHub Desktop.
Save odlp/6825538 to your computer and use it in GitHub Desktop.
Ruby - examples of cascading & namespacing
# 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
# 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