在许多情况中,当你设计你的应用程序时,你可能想实现一个方法仅为一个对象内部使用而不能为另外一些对象使用。Ruby提供了三个关键字来限制对方法的存取。
classRectangle attr_accessor:height,:width definitialize(hgt,wdth) @height=hgt @width=wdth end defarea() @height*@width end private#开始定义私有方法 defgrow(heightMultiple,widthMultiple) @height=@height*heightMultiple @width=@width*widthMultiple return"Newarea:"+area().to_s end public#再次定义公共方法 defdoubleSize() grow(2,2) end end |
irb(main):075:0>rect2=Rectangle.new(3,4) =>#<Rectangle:0x59a3088@width=4,@height=3> irb(main):076:0>rect2.doubleSize() =>"Newarea:48" irb(main):077:0>rect2.grow() NoMethodError:privatemethod'grow'calledfor#<Rectangle:0x59a3088@width=8,@height=6> from(irb):77 from:0 |