-
-
Save havenwood/f177132c0f7ebaae76ea to your computer and use it in GitHub Desktop.
Explanation of Modules
This file contains 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
# 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