super in ruby

The “super” keyword in ruby behaves a little differently than other languages. Instead of returning an instance of the superclass, it checks all the way up the ancestry tree to find the inherited method.

def foo(a)

Is the same as

void foo(a)

  • supper is a keyword, not a method; Methods can be overridden in subclasses of ruby.

  • ancestor tree: An ancestor of a class is either the class itself, a module included by any of the class’s ancestors or the superclass of any of the class’s ancestors. In short the ancestors of a class are all the classes and modules in which ruby will look for the method definition when you call a method on an object of that class.

module Vehicular
  def move_forward(n)
    @position += n

class Vehicle
  include Vehicular  # Adds Vehicular to the lookup path

class Car < Vehicle
  def move_forward(n)
    puts "Vrooom!"
    super            # Calls Vehicular#move_forward
puts Car.ancestors.inspect

# Output
# [Car, Vehicle, Vehicular, Object, Kernel, BasicObject]

Note the inclusion of the Vehicular Module object!

One thought on “super in ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s