Search⌘ K

Modules

Explore the concept of modules in Ruby and how they allow you to include reusable code in classes or other modules. Understand the difference between using modules and inheritance for code sharing, improving your grasp of object-oriented programming principles in Ruby.

We'll cover the following...

Definition

A module is a chunk of code we can include in a class or in another module:

Ruby
# MyModule contains logic for robot, human, and dog
module MyModule
attr_accessor :x, :y
def initialize(options={})
@x = options[:x] || 0
@y = options[:y] || 0
end
def right
self.x += 1
end
def left
self.x -= 1
end
def up
self.y += 1
end
def down
self.y -= 1
end
end
class Robot
include MyModule
def label
'*'
end
end
class Dog
include MyModule
def up
end
def left
end
def label
'@'
end
end
class Human
include MyModule
def label
'H'
end
end

In ...