Intro to Ruby - Modules

Ruby

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

Tags:

Tuesday, March 3rd, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.