include | extend | |
---|---|---|
API | include(module, ...) → self | extend(module, ...) → obj |
Behavior | Invokes 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 class | Methods 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
-
Module#method-i-include by ruby-doc.org
-
Object#method-i-extend by ruby-doc.org