Include/Extend in Ruby Modules
April 23, 2011
I have always confused my self when to use include or extend when mixin methos of a class.
include() mixes methods into the instances of the base object.
extend() mixes methods into the base object itself.
For example,
module Color
def green
"I'm green"
end
end
By including Greeter into SomeClass, we make it so that we can now call hello() on instances of SomeClass.
class SomeClass include Color end SomeClass.new.green #=> "I'm green"
Extending AnotherClass with Greeter would allow us to call the hello method directly at the class level, as in the example below.
class AnotherClass extend Color end AnotherClass.green #=> "I'm green"
Advertisement
No comments yet