Ruby is an object-oriented language that supports inheritance. It supports single class inheritance, but multiple class inheritance is not supported.
Inheritance offers reusability. This means that the functions and variables already declared in one class can be reused in another class by making it a child of that class. This prevents the need for extra, redundant code in the new class that is being declared.
Every class in Ruby has a parent class by default. Since Ruby 1.9 version, BasicObject class is the parent class of all other classes in Ruby.
Inheritance involves the use of super and sub-classes.
In the case that both the super class and the sub class have a function of the same name, the method associated with the sub class will be executed, i.e. the inherited function will be over-ridden.
This is a special feature of inheritance in Ruby.
The following code shows how a subclass object can access a super class function:
# Inheritance in Ruby# this is the super classclass Educative# constructor of super classdef initializeputs "Super class constructor"end# method of the superclassdef super_adder(x, y)puts "Using method of superclass:"return x+yendend# subclass or sub classclass Edpresso < Educative# constructor of sub classdef initializeputs "Sub class constructor"endend# creating object of superclassEducative.new# creating object of subclasssub_obj = Edpresso.new# calling the method of super class using sub class objectadded = sub_obj.super_adder(2,3)print "sum = ", added
In the above code, the class Edpresso
inherits the base class Educative
using the <
symbol.
Free Resources