Quick Start to Ruby programming language-method Access Control

Source: Internet
Author: User

In many cases, when you design your applicationProgramYou may want to implement a method that is only used inside an object rather than other objects. Ruby provides three keywords to restrict access to methods.

    • · PRIVATE: Only methods accessible to this object.
    • · Protected: a method that can be accessed by this object and its class instances and directly inherited sub-classes.
    • · Public: the method that can be accessed by any object (public is the default setting for all methods ).

These keywords are inserted between two methodsCode. All methods defined from the private keyword are private until another accesskey keyword appears in the code. For example, in the following code, the accessor and area methods are both public by default, while the grow method is private. Note that the doublesize method is explicitly specified as public. The initialize method of a class is automatically private.

Class rectangle
Attr_accessor: height,: width
Def initialize (HgT, wdth)
@ Height = HgT
@ Width = wdth
End
Def area ()
@ Height * @ width
End
Private # start to define private methods
Def grow (heightmultiple, widthmultiple)
@ Height = @ height * heightmultiple
@ Width = @ width * widthmultiple
Return "New Area:" + area (). to_s
End
Public # define public methods again
Def doublesize ()
Grow (2, 2)
End
End

 

As shown below, doublesize can be executed on the object, but any direct call to grow is rejected and an error is returned.

IRB (main): 075: 0> rect2 = rectangle. New (3, 4)
==#< Rectangle: 0x59a3088 @ width = 4, @ Height = 3>
IRB (main): 076: 0> rect2.doublesize ()
=> "New Area: 48"
IRB (main): 077: 0> rect2.grow ()
Nomethoderror: Private method 'grow' called for # <rectangle: 0x59a3088 @ width = 8, @ Height = 6>
From (IRB): 77
From: 0

By default, instances and class variables are private in Ruby unless the property accessor and mutator are provided.

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.