Ruby's private and protected

Source: Internet
Author: User

Today, the following Program has made me struggle for a long time. The concept of private in Ruby is really strange...

Class Test private def test_print puts 'test' endendclass Test2 <test def test_print2 # self. test_print # => you cannot call endendTest2.new by adding self here. private method 'test _ print' called for # (NoMethodError) test_print # => endendTest2.new can be called without self. test_print2

If no self is added, private can also call the method of the parent class?

In Ruby, private is different from Java or other languages, and sub-classes can also be called, but callers cannot be specified.

Turning over The Ruby Way, The book says:

Private: the class and subclass can be called, but the private method cannot specify the caller. The default value is self.

Protected: both classes and subclasses can be called. You can specify callers.

This explains why the above Code makes an error when calling with self, and can be correctly executed without adding self.

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.