Difference between Include/Extend Modules in Ruby

ruby

June 23, 2019  |  2 min read

includeextend
APIinclude(module, ...) → selfextend(module, ...) → obj
BehaviorInvokes Module.append_features on each parameter in reverse order.Adds to obj the instance methods from each module given as a parameter.
*When used inside of a class...Methods become instance methods of the classMethods become class methods of the class
When used upon an instance...Adds to obj the instance methods from each module given as a parameter.

Code Example

module Flyable
  def fly
    puts 'I am flying!'
  end
end
 
module Greetable
  def say_hi
    puts 'Hello!'
  end
end
 
 
class Car
  include Flyable
end
 
class Airplane
  extend Flyable
end
 
 
Car.new.fly # outputs "I am flying!"
Car.fly # undefined method `fly' for Car:Class (NoMethodError)
 
Airplane.new.fly # undefined method `fly' for #<Airplane:0x00007f8f59118998> (NoMethodError)
Airplane.fly # "I am flying!"
 
instance = Airplane.new.extend(Flyable, Greetable)
instance.fly # "I am flying!"
instance.say_hi # "Hello!"

Refs