Modules and Class Composition

suggest change

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 # prints: baz_method called!
new_baz.bar_method # prints: bar_method called!
new_baz.foo_method # prints: foo_method called!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents