Inheritance Hierarchy

By default, Ruby classes inherit directly from Object:

class Foo; end

puts Foo.ancestors.inspect
# => [Foo, Object, Kernel, BasicObject]

Foo.ancestors.inspect shows us that Foo inherits from Object.

Effects of

include

Include a modules methods as instance methods in the current Module/Class

module Foo
  def bar
    puts "bar"
  end
end

class Bar
  include Foo
end

Bar.new.bar
# => "bar"

extend

Include a modules methods as class methods in the current Module/Class

module Foo
  def bar
    puts "bar"
  end
end

class Bar
  extend Foo
end

Bar.bar
# => "bar"

prepend

  • Prepend the module to the class’s ancestry
  • Prepended modules methods can’t be (acidentally) overwritten (unlike included modules)
module Foo
  def bar
    puts "bar in Foo"
  end
end

class Bar
  prepend Foo

  def bar
    puts "bar in Bar"
  end
end

Bar.new.bar
# => "bar in Foo"

super

Calls the parent classes version of the current method

class Foo
  def bar
    "foo"
  end
end

class Bar < Foo
  def bar
    "bar " + super
  end
end

puts Bar.new.bar
# => "bar foo"

Method Dispatch

Ruby looks up methods in the following order:

  1. Methods defined in the object’s singleton class (i.e. the object itself)
  2. Modules mixed into the singleton class in reverse order of inclusion
  3. Methods defined by the object’s class
  4. Modules included into the object’s class in reverse order of inclusion
  5. Methods defined by the object’s superclass, i.e. inherited methods

Sources / Things to look at

Practicing Ruby:

Misc Blogs: