Monday, July 16, 2012

Modules in Ruby - an overview

We can define any number of methods in a module. It simply holds all the defined methods and we can include/extend it in any class.
If you want to use all module methods access by an instance then include the module in that class.
If you want to use all module methods access by an class then extend the module in that class.
module Foo
  def foo
    puts 'foo called!'
  end
end

class Bar
  include Foo
end

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

class Baz
  extend Foo
end

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


Hope this helps. Happy learning & coding :)