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").walkinclude 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
- Defining Modules
- include and extend
- Comparable and Enumerable
- prepend and Method Resolution