Basics of Include and Extend in Ruby on Rails

Include is for adding methods to an instance of a class and extend is for adding class methods. Let’s take a look at a small example.

module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for # 

As you can see, include makes the foo method available to an instance of a class and extend makes the foo method available to the class itself.

Comments

Popular posts from this blog

Interview Question on Ruby on Rails

Inserting and Moving elements inside Ruby Array