Ruby Overriding Methods


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:
