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.