0Pricing
Ruby Academy · Lesson

include and extend

Mixing in behavior.

Mixing In Behavior

The real power of modules is the mixin: sharing methods across classes without inheritance. The two main tools are include and extend.

module Walkable
  def walk
    "#{name} is walking"
  end
end
class Person
  include Walkable
  attr_reader :name
  def initialize(name)
    @name = name
  end
end
puts Person.new("Ada").walk

include Adds Instance Methods

include mixes a module's methods in as instance methods. Every object of the class gains them.

module Sayable
  def say(msg)
    "#{msg}!"
  end
end
class Dog
  include Sayable
end
puts Dog.new.say("Woof")

All lessons in this course

  1. Defining Modules
  2. include and extend
  3. Comparable and Enumerable
  4. prepend and Method Resolution
← Back to Ruby Academy