Intro to Ruby - Modules

Overview
Modules allow you to easily mix in additional functionality to your classes without having to deal with complicated superclass hierarchies or interfaces (if you come from the Java world). It is also a clever way of supporting multiple inheritance and keeping your code DRY as you can reduce functionality to small, self-contained pieces of code that can be shared amongst several objects easily. Take some time to study and play with the code below. Notice how super and sub-classes are uses along with the module.
Code
# Setup
module Communicate
def speak
puts "Speaking..."
end
def sing
puts "Singing..."
end
end
class Human
include Communicate
attr_accessor :arms
attr_accessor :legs
def initialize arms = 2, legs = 2
@arms = arms
@legs = legs
@@label = "This is the class label for a variable."
end
def self.what_am_i
puts "I am a #{LABEL}."
end
def describe
puts "I have #{@arms} arm(s)."
puts "I have #{@legs} leg(s)."
end
def name
self.class.name
end
end
class JohnDoe < Human
def blink
puts "#{name} is blinking rapidly."
end
end
# Initialization
jd = JohnDoe.new 1, 1
# The following demonstrates execution of the "describe" method as inherited from the Human superclass.
puts "01 Superclass Methods\n\n"
jd.describe
# The following demonstrations execution of the "speak" and "sing" methods as mixed in from the Communicate module.
puts "\n02 Module Methods\n\n"
jd.speak
jd.sing
# The following prints the name of the class (notice how self is relative to the object being called).
puts "\n02 Simple 'Self' Example\n\n"
puts jd.name
Output
01 Superclass Methods
I have 1 arm(s).
I have 1 leg(s).
02 Module Methods
Speaking...
Singing...
02 Simple 'Self' Example
JohnDoe
Download
The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 10-modules.rb.
What’s Next
Conditionals
Article Series - Intro to Ruby
- Intro to Ruby - Getting Started
- Intro to Ruby - Strings
- Intro to Ruby - Numbers
- Intro to Ruby - Ranges
- Intro to Ruby - Arrays
- Intro to Ruby - Hashes
- Intro to Ruby - Variables and Scopes
- Intro to Ruby - Methods
- Intro to Ruby - Blocks
- Intro to Ruby - Classes
- Intro to Ruby - Modules
- Intro to Ruby - Conditionals
- Intro to Ruby - Loops
- Intro to Ruby - Exceptions
- Intro to Ruby - Testing
- Intro to Ruby - Next Steps
No comments yet.
Leave a comment
You must be logged in to post a comment.
Search
Categories
- Adventures
(112)
- Announcements
(36)
- Business
(19)
- Electronics
(21)
- Epicurean
(10)
- Games
(3)
- Literature
(1)
- Mechanical
(4)
- Meetups
(18)
- Movies
(2)
- Music
(26)
- Photography
(1)
- Services
(27)
- Software
(132)