Skip to content

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"
Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: