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 对象打交道.这个例子当然过于简单;访问控制的优点只有当我们开始写更复杂和有趣的类时方能显现出来.