Ruby Inheritance Rules Simplified

No Comments

A simple principle to understand Ruby inheritance is LIFO (Last In First Out).

 

  1. Ruby will search the object you’re calling it from
  2. It will search it in any included modules, starting with the last loaded module
  3. It will go in the superclass (technically, modules get in the inheritance hierarchy as well, but whatever)

When the method is found, the search stops.

 

A Note About Calling super.
The same rule applies if you use super. If you have the same method defined in both module and a parent class, the module method will be called.
Here’s a simple example:

module Test
  def abc
    puts 'abc from Module'
  end
end

class TestClassParent
  def abc
    puts 'abc from parent'
  end
end

class TestClassChild < TestClassParent
  include Test

  def abc
    super
  end
end


TestClassChild.new.abc

Running this will result in:

abc from Module

Categories: Ruby

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Loading Facebook Comments ...