Ruby include and extend

My employer, Razoo, treated its developers to RailsConf 2010 this year. Very late the second night of the conference (the first night I was there–we skipped the tutorials), I saw Yehuda Katz give an impromptu Birds of a Feather talk about upcoming changes in Rails. It was good, but the thing I remember most clearly was his explanation of include and extend in Ruby. He let code do the explaining:

# a module with a method
module Says
  def hello
    puts 'hello'
  end
end

# a class we want to have the method (not an instance; the class)
class Person
end

# (our end goal)
class Person
  def self.hello
    puts 'hello'
  end
end

# there are two ways to achieve this
# using extend
class Person
  extend Says
end

# or using include
class Person
  class << self
    include Says
  end
end

So, in short, include just includes the module’s methods as instance methods and extend includes the module’s methods as class methods. I always do better with examples than reading technical documentation!

Advertisements

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