Skip to content

Instantly share code, notes, and snippets.

@havenwood

havenwood/modules.rb Secret

Last active Jan 3, 2016
Embed
What would you like to do?
Explanation of Modules
# Prerequisite explanations: String, Integer, Range, #puts, #rand
# This is how you create a module named Example:
module Example
end
# This is how you create methods in your module:
module Example
def Example.a_method
"i am a string"
end
def Example.another_method
42
end
end
# And you can call those methods:
Example.a_method
#=> "i am a string"
Example.another_method
#=> 42
# But if you changed your module name, all the methods would need to be renamed:
module AnotherExample
def Example.a_method
"i am a string"
end
def Example.another_method
42
end
end
AnotherExample.a_method
# NoMethodError: undefined method `a_method' for AnotherExample:Module
# It is better to use `self.a_method` instead of `Example.a_method` to avoid this brittleness:
module AnotherExample
def self.a_method
"i am a string"
end
def self.another_method
42
end
end
AnotherExample.a_method
#=> "i am a string"
# This works just as before because `self` refers to the module it is enclosed in:
module AnotherExample
puts self
end
# AnotherExample
# Now we'll define a method called `roll` on a module called `Dice`:
module Dice
def roll
rand 1..6
end
end
# Without a `self` in front of `roll` you can't call the method directly:
Dice.roll
# NoMethodError: undefined method `roll' for Dice:Module
# But you can use it in another module with `extend`:
module BoardGame
extend Dice
end
BoardGame.roll
#=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.