Skip to content

Instantly share code, notes, and snippets.

@sk187
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sk187/d964bb78f1948216872f to your computer and use it in GitHub Desktop.
Save sk187/d964bb78f1948216872f to your computer and use it in GitHub Desktop.
Ruby Modules
# 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