在许多情况中,当你设计你的应用程序时,你可能想实现一个方法仅为一个对象内部使用而不能为另外一些对象使用。Ruby提供了三个关键字来限制对方法的存取。
· Private:只能为该对象所存取的方法。 · Protected:可以为该对象和类实例和直接继承的子类所存取的方法。 · Public:可以为任何对象所存取的方法(Public是所有方法的默认设置)。 class Rectangleattr_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。