Ruby 访问控制

“protected”和“private”之间的区别很微妙,如果方法是保护的,它可以被定义了该方法的类或其子类的实例所调用。如果方法是私有的,它只能在当前对象的上下文中被调用--不可能直接访问其他对象的私有方法,即便它与调用者都属同一个类的对象。

Ruby和其他面向对象语言的差异,还体现在另一个重要的方面。访问控制实在程序运行时动态判定的,而非静态判定。只有当代码试图执行受阻的方法,你才会得到一个访问违规。

有两种不同的方式定义函数的访问级别

首先

class MyClass

             def method1  #default is 'public'

                #...

             end

      protected              #subsequent methods will be 'protected'

              def method2  #will be 'proteced'

                 #...

               end 

       private                 #subsequent methods will be 'private'

              def method3  #will be 'private'

                 #...

               end 

        public                  #subsequent methods will be 'public'

              def method4  #will be 'public'

                 #...

               end 

end

另外,你可以通过将方法名作为参数列表传入访问控制函数来设置它们的访问级别。

class MyClass

  def method1

    #..

   end

#...and so on

public         :method1, :method2

protected   :method3

private         :method4

end

原文地址:https://www.cnblogs.com/timsheng/p/2592292.html