ruby> class Test
| def times_two(a)
| print a," times two is ",engine(a),"\n"
| end
| def engine(b)
| b*2
| end
| private:engine # this hides engine from users
| end
Test
ruby> test = Test.new
#<Test:0x4017181c>
ruby> test.engine(6)
ERR: (eval):1: private method `engine' called for #<Test:0x4017181c>
ruby> test.times_two(6)
6 times two is 12.
nil
開始時,我們本希望test.engine(6)返回12,但隨後當我們扮演一個Test對象使用者時我們瞭解到engine是不可訪問的(inaccessible).只有Test的其它方法,像 times_two可以使用 engine.我們被要求保持程式的外部介面,也就是 times_two這些方法.管理此類的程式員可以自由的更改engine(這裡,可能把b*2改為b+b,假設這樣可以提高效能)而不影響使用者與 Test 對象打交道.這個例子當然過於簡單;存取控制的優點只有當我們開始寫更複雜和有趣的類時方能顯現出來.