Ruby's super syntax is really flexible.

Source: Internet
Author: User

Unlike Java, super in Ruby replaces not the parent class, but the method with the same name as the current method in the parent class. In Ruby, super is used flexibly. When super is used, without any parameters (and no parentheses), the actual function is to automatically call the current method in the parent class and pass the current parameter over, that is
Super. Thismethod (param1, param2. ..) can be simplified to a super in ruby, which is very convenient.

Example

Class A <string
Def to_s
Super + "__"
End
End

A = A. New ('OK ')
P a. to_s

If the parameters of the method in the parent class are different from those in the subclass class, you must explicitly call the input parameters.

Note: Super. somemethod syntax is not available in ruby, because Super is already the parent class method, so when using super, if the current method is added, therefore, super commands cannot be used. use self instead (the parent class method is directly inherited to self)
 

Class B <string
Def to_s
Super + "__"
End
Def newmethod # New Method
Self + "__"
End
End

In addition, the super command ignores method access control. That is to say, super can directly call the private method in the parent class. It seems a little flexible.

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.