· 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。