Ruby's Method access control

Source: Internet
Author: User

In many cases, when you design your application, you may want to implement a method that is used only for internal use by one object and not for other objects. Ruby provides three keywords to restrict access to methods.

Private: A method that can only be accessed for this object.

Protected: A method that can be accessed for this object and class instances and directly inherited subclasses.

Public: A method that can be accessed for any object (public is the default setting for all methods).

These keywords are inserted in the code between the two methods. All methods defined from the Private keyword are private until another access control keyword appears in the code. For example, in the following code, the accessor and area methods are public by default, and the Grow method is private. Note that this 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 #开始定义私有方法
def grow (heightMultiple, widthMultiple)
@height = @height * heightMultiple
@width = @width * widthMultiple
return "New area:" + area().to_s
end
public #再次定义公共方法
def doubleSize ()
grow(2,2)
end
end

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

irb(main):075:0> rect2=Rectangle.new(3,4)
=> #
irb(main):076:0> rect2.doubleSize()
=> "New area: 48"
irb(main):077:0> rect2.grow()
NoMethodError: private method 'grow' called for #
from (irb):77
from :0

By default, in Ruby, both instance and class variables are private 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.