在許多情況中,當你設計你的應用程式時,你可能想實現一個方法僅為一個對象內部使用而不能為另外一些對象使用。Ruby提供了三個關鍵字來限制對方法的存取。
- · 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。