Detailed explanation of rudy overload Methods

Source: Internet
Author: User

In the subclass, we can modify the object behavior by reloading the parent class method.

Ruby> class Human
| Def identify
| Print "I'm a person. \ n"
| End
| Def train_toll (age)
| If age <12
| Print "CED 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


If we only want to enhance the identify method of the parent class instead of Completely replacing it, 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 can also let us pass parameters to the original method. There are sometimes two types of people here...

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.