Private, protected, and public in Ruby class

Source: Internet
Author: User

Private
Private functions can only be called in the context of the class and subclass, and can only be accessed through self.

This means that the private function can only be accessed within the object.

The access permission of the object instance variable (@) is private.
Copy codeThe Code is as follows:
Class AccessTest
Def test
Return "test private"
End
Def test_other (other)
"Other object" + other. test
End
End
T1 = AccessTest. new
T2 = AccessTest. new

P t1.test # => test private

P t1.test _ other (t2) # => other object test private


# Now make 'test' private

Class AccessTest
Private: test
End

P t1.test _ other (t2) # error in 'test _ other ': private method 'test' called for # <AccessTest: 0x292c14> (NoMethodError)


Protected
The protect function can only be called in the context of the class and subclass, but can be in the form of other_object.function. (This is equivalent to the private mode of C ++)

The key is that the protected function can be used inside other objects of the same type (including subclasses.

# Now make 'test' protect

Class AccessTest
Protected: test
End

P t1.test _ other (t2) # other object test private

Public
The public function can be called anywhere. The default access permission for member functions and constants is public.

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.