Ruby - Class Overriding Methods

Introduction

When a method in one class replaces a method of the same name in an ancestor class, it is said to override that method.

You can override methods that are defined in the standard class library such as to_s as well as methods defined in your own classes.

To add new behavior to an existing method, remember to call the superclass's method using the super keyword at the start of the overridden method.

Demo

class MyClass 
   def sayHello #  w w w  . jav a  2s.  c o  m
      return "Hello from MyClass" 
   end 
                        
   def sayGoodbye 
      return "Goodbye from MyClass"  
   end 
end 


class MyOtherClass < MyClass 
    def sayHello      #overrides (and replaces) MyClass.sayHello 
        return "Hello from MyOtherClass" 
    end 
        # overrides MyClass.sayGoodbye   but first calls that method with super. 
    def sayGoodbye    
        return super << " and also from MyOtherClass" 
    end 
        # overrides default to_s method 
    def to_s 
        return "I am an instance of the #{self.class} class" 
    end 
end

Related Topic