Ruby Language Modules and Class Composition


Example

You can use Modules to build more complex classes through composition. The include ModuleName directive incorporates a module's methods into a class.

module Foo
  def foo_method
    puts 'foo_method called!'
  end
end

module Bar
  def bar_method
    puts 'bar_method called!'
  end
end

class Baz
  include Foo
  include Bar

  def baz_method
    puts 'baz_method called!'
  end  
end

Baz now contains methods from both Foo and Bar in addition to its own methods.

new_baz = Baz.new
new_baz.baz_method #=> 'baz_method called!'
new_baz.bar_method #=> 'bar_method called!'
new_baz.foo_method #=> 'foo_method called!'