Monday 7 October 2013

Method Dispatch in Ruby (include, extend, super and prepend)


Include 

Include  is for adding methods to an instance of a class

Extend

Extend is for adding class methods. (like self. )

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 #<Baz:0x1e708>
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.


References :
http://blog.jcoglan.com/2013/05/08/how-ruby-method-dispatch-works/
http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

No comments:

Post a Comment