Sunday, December 30, 2007

Understanding include and extend in Ruby

I was watching a presentation by Dave Thomas called, "MetaProgramming - Extending Ruby for Fun and Profit", and realized that my understanding of include and extend is mixed up.

My Wrong Understanding
I thought "extend" will add methods from a module into a class as instance methods and "include" will add them as class methods.

Correct Understand:
"extend" adds methods from a module into a class as class methods.
"include" adds methods from a module into a class as instance methods.

It is quite easy to demonstrate this actually.

module SomeModule
def hi
puts "hello"
end
end

class ExtendSample
extend SomeModule
end

ExtendSample.hi

class IncludeSample
include SomeModule
end

IncludeSample.new.hi

No comments: