Ruby journey (5) Encapsulation

Source: Internet
Author: User

There are three types of modifying keywords for Ruby member access, which are the same as C.
1 private can only be the method called by this object
2 protected can only be called for this object and its sub-objects
3. Public allows any object to call methods.

Different from C #, the ruby access modifier starts to work from the definition and ends when the next access modifier appears, for example

Class Greeter
Def Initialize
End

Private
Def Sayhi ()
Puts " Hi "
End

Def Saybye ()
Puts " Bye "
End

Public
Def Say ()
Sayhi
Saybye
End

End

G = Greeter. New
G. Say # Output Hi Bye
G. sayhi # Error because the sayhi isn' t publics Member

Initialize is private by default. Other methods are public member variables and class variables are private by default. Use attr_reader or attr_accessor to increase read/write control.

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.