Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby - Redefinition of methods

Inheritance
Prev
Contents
Contents
Access control
Next

 Ruby user's guideRedefinition of methods 

In a subclass, we can change the behavior of the instances by redefining superclass methods.

ruby> class Human
    |   def identify
    |     print "I'm a person.\n"
    |   end
    |   def train_toll(age)
    |     if age < 12
    |       print "Reduced fare.\n";
    |     else
    |       print "Normal fare.\n";
    |     end
    |   end
    | end
   nil
ruby> Human.new.identify
I'm a person.
   nil
ruby> class Student1<Human
    |   def identify
    |     print "I'm a student.\n"
    |   end
    | end
   nil
ruby> Student1.new.identify
I'm a student.
   nil

Suppose we would rather enhance the superclass's identify method than entirely replace it. For this we can use super.

ruby> class Student2<Human
    |   def identify
    |     super
    |     print "I'm a student too.\n"
    |   end
    | end
   nil
ruby> Student2.new.identify
I'm a human.
I'm a student too.
   nil

super lets us pass arguments to the original method. It is sometimes said that there are two kinds of people...

ruby> class Dishonest<Human
    |   def train_toll(age)
    |     super(11) # we want a cheap fare.
    |   end
    | end
   nil
ruby> Dishonest.new.train_toll(25)
Reduced fare. 
   nil

ruby> class Honest<Human
    |   def train_toll(age)
    |     super(age) # pass the argument we were given
    |   end
    | end
   nil
ruby> Honest.new.train_toll(25)
Normal fare. 
   nil


Inheritance
Prev
Contents
Contents
Access control
Next

 
 
  Published under the terms of the OpenLDAP Public License Design by Interspire