· Private:只能为该对象所存取的方法。
· Protected:可以为该对象和类实例和直接继承的子类所存取的方法。
· Public:可以为任何对象所存取的方法(Public是所有方法的默认设置)。
这些关键字被插入在两个方法之间的代码中。所有从private关键字开始定义的方法都是私有的,直到代码中出现另一个存取控制关键字为止。例如,在下面的代码中,accessor和area方法默认情况下都是公共的,而grow方法是私有的。注意,在此doubleSize方法被显式指定为公共的。一个类的initialize方法自动为私有的。
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
如下所示,doubleSize可以在对象上执行,但是任何对grow的直接调用都被拒绝并且返回一个错误。
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
默认情况下,在Ruby中,实例和类变量都是私有的,除非提供了属性accessor和mutator。
