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)
super
end

Is the same as

void foo(a)
{
closest_ancestor_that_has_foo_method.foo(a)
}

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

http://www.rubyinair.com/2011/04/super-is-keyword-not-method-call.html

  • 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.

http://ruby-doc.org/docs/keywords/1.9/files/keywords_rb.html#M000034

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

class Vehicle
  include Vehicular  # Adds Vehicular to the lookup path
end

class Car < Vehicle
  def move_forward(n)
    puts "Vrooom!"
    super            # Calls Vehicular#move_forward
  end
end
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:

WordPress.com Logo

You are commenting using your WordPress.com 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