A brief talk on Ruby's private and Protected_ruby topics

Source: Internet
Author: User

The following procedure has kept me in the middle of a long time, the concept of private in Ruby is really strange ...

Class Test Private
 def test_print
  puts ' test '
 end

class Test2 < Test
 def Test_print2
  # Self.test_print #=> here Plus self cannot invoke, private method ' Test_print ' called for # (Nomethoderror)
  test_print #=& Gt You can call end end Test2.new.test_print2 without self

 

Why not add self, private can also invoke the method of the parent class?

Originally in Ruby, Private is not the same as Java or other languages, subclasses can be invoked, but callers cannot be specified.

"The Ruby Way," the book says:

Private: Both classes and subclasses can be invoked, but private methods cannot specify the caller, and the default is self.
Protected: Both classes and subclasses can be invoked to specify the caller.

This explains why, in the above code, a call with self would be an error without self being able to execute correctly.

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.