Ruby Overriding Methods


Method overriding, in object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.

Here's an example p037xmtdovride.rb:

The method a in class B overrides the method a in class A.

Usage of super

The way super handles arguments is as follows:

  • When you invoke super with no arguments Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. It automatically forwards the arguments that were passed to the method from which it's called.
  • Called with an empty argument list - super()-it sends no arguments to the higher-up method, even if arguments were passed to the current method.
  • Called with specific arguments - super(a, b, c) - it sends exactly those arguments.

An example (p038bicycle.rb) from Ruby for Rails book highlights this:

The output is:

We shall be talking in depth about attr_reader later.

Redefining Methods

(Adapted from David Black's book, Ruby For Rails)

Nothing stops you from defining a method twice. Program p038or.rb

What happens when we call mtd on an instance of OR? Let's find out:

The printed result is the Second definition of method mtd. The second definition has prevailed: We see the output from that definition, not from the first. Nothing stops you from defining a method twice, however the new version takes precedence.

Abstract class

In Ruby, we can define an abstract class that invokes certain undefined "abstract" methods, which are left for subclasses to define. For example:

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.