๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Include and Extend

The beginner course mixed module methods into a class with include. This lesson adds extend, which lends the same methods to the class itself.

include lends to objects

Painter mixes Brushwork in with include. A painter object then calls stroke as its own method.

module Brushwork
  def stroke
    puts "The brush moves"
  end
end
class Painter
  include Brushwork
end
painter = Painter.new
painter.stroke

extend lends to the class

Gallery extends Brushwork here. The class itself calls stroke, and no gallery object is built.

module Brushwork
  def stroke
    puts "The brush moves"
  end
end
class Gallery
  extend Brushwork
end
Gallery.stroke

One module, both jobs

Singer includes Songbook, and Stage extends it. The singer object and the stage class both call chorus.

module Songbook
  def chorus
    puts "Sing the chorus"
  end
end
class Singer
  include Songbook
end
class Stage
  extend Songbook
end
singer = Singer.new
singer.chorus
Stage.chorus

Example

module Signals
  def beep
    puts "Beep once"
  end
  def flash
    puts "Light flashes"
  end
end
class Alarm
  include Signals
end
class Tower
  extend Signals
end
alarm = Alarm.new
alarm.beep
Tower.beep
Tower.flash
alarm.flash

Key points

  • include lends module methods to objects of a class.
  • extend lends module methods to the class itself.
  • Objects call included methods as their own methods.
  • The class calls extended methods through the class name.
  • An extended method does not reach objects of the class.
  • One module can serve both jobs in one program.

In this example, Signals holds beep and flash. Alarm includes Signals, so an alarm object calls both methods. Tower extends Signals, so the Tower class calls both methods through its own name.

Note

include and extend can appear in different classes that share one module.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does extend Signals do inside a class?