Using Superclass’s Method in Ruby

Ruby allows you to extend the behavior of the superclass instead of just overriding it and as a result replacing it. Ruby relies on keyword “super” to allow superclass methods to be available in the class we are calling from.

When we call super from within our own class, ruby will pass all the arguments to the same method of the superclass in exactly same way as they were received by subclass.

Example how superclass’s method can be used from within subclass is shown below.

class Car
 def speed(miles, hours)
  speed = miles/hours
  return speed
end

class FastCar
 def speed(miles, hours)
  hours+=hours*2
  super(miles, hours)
 end

We can see from the example above that super was called with arguments after we performed additional calculations. This is one way of passing parameters. If we are to omit passing of the parameters and simply calling super from our FastCar.speed method, then super will take on the subclass parameters.

The “super” call can be made anywhere within method unlike Java implementation where you need to call super on the top. In fact, you can call super multiple times within a method. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…