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.