Books / Ruby for Beginners / Chapter 35

Modules

Module is a chunk of code you can include in a class or into another module:

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 the program above we defined the module with “module... end” syntax and included the module to our classes with “include” keyword. Class diagram would look like this:

Class diagram using modules, three classes share common functionality

Visually it looks pretty much like inheritance. However, using inheritance just to copy/share the code is not cool, it’s just not the right tool. It’s better to be honest about what are you doing. With modules you are honest and you admit: yes, I’m just copying the code, there is no any inheritance involved.


Licenses and Attributions


Speak Your Mind

-->