Last active
August 29, 2015 14:17
-
-
Save sk187/d964bb78f1948216872f to your computer and use it in GitHub Desktop.
Ruby 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
# Modules are similar to classes but they can't create new instances | |
# nor can they have subclasses. They are used to store things such as | |
# methods and constants until we need them. | |
# Modules let classes "inherit" behaviors as needed also known as mixins | |
module Code | |
# Constants can be defined in modules in ALL CAPS with _ for multiple words | |
CURRENT_JOB = "programmer" | |
def code | |
# #{@name} is allowing me to display @name's attribute. If it was just @name, the puts | |
# method would return @name as a string, not the attribute of @name | |
# "Because @name is a programmer, @name is coding." | |
puts "Because #{@name} is a #{CURRENT_JOB}, #{@name} is coding." | |
end | |
end | |
class Person | |
# the include Code allows the class Person to have access to the module Code | |
include Code | |
def initialize(name) | |
@name = name | |
end | |
end | |
# Creating a new instance of Person | |
sung = Person.new("Sung") | |
sung.code | |
# Returns | |
"Because Sung is a programmer, Sung is coding." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment