對象實例變量(@)的訪問權限就是 private。 代碼如下: class AccessTest def test return “test private” end def test_other(other) “other object ”+ other.test end end t1 = AccessTest.new t2 = AccessTest.new
p t1.test # => test private
p t1.test_other(t2) # => other object test private
# Now make 'test' private
class AccessTest private :test end
p t1.test_other(t2) #錯誤 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)
Protected protect 函數只能 在本類和子類的 上下文中調用,但可以使用 other_object.function的形式。(這跟 C++ 的 private 模式等同)