Private, protected, Public_ruby topics in Ruby's class

Source: Internet
Author: User
Private
Private functions can only be invoked in the context of this class and subclass, and can only be accessed by self.

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

The access rights of an object instance variable (@) are private.
Copy Code code 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) #错误 in ' test_other ': Private method ' Test ' called for #<accesstest:0x292c14> (Nomethoderror)


Protected
The Protect function can only be invoked in the context of this class and subclass, but it may use the form of other_object.function. (This is equivalent to C + + private mode)

The key is that the protected function can be used inside other objects of the same class (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 invoked anywhere. The default access rights for member functions and constants are 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.