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"

By including Greeter into SomeClass, we make it so that we can now call hello() on instances of SomeClass.

class SomeClass
  include Color
end #=> "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 #=> "I'm green"
No comments yet

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: