Ruby - 受保护的方法

4

我有以下的Ruby程序:

class Access

def retrieve_public
puts "This is me when public..."
end

private
def retrieve_private
puts "This is me when privtae..."
end

protected
def retrieve_protected
puts "This is me when protected..."
end

end


access = Access.new
access.retrieve_protected

当我运行它时,我得到了以下内容:
accessor.rb:23: protected method `retrieve_protected' called for #<Access:0x3925
758> (NoMethodError)

为什么会这样呢?
谢谢。
3个回答

14

因为你只能从该对象的实例方法内部,或该类(或其子类)的另一个对象中直接调用受保护的方法。

class Access

  def retrieve_public
    puts "This is me when public..."
    retrieve_protected

    anotherAccess = Access.new
    anotherAccess.retrieve_protected 
  end

end

#testing it

a = Access.new

a.retrieve_public

# Output:
#
# This is me when public...
# This is me when protected...
# This is me when protected...

13
这就是 Ruby 中保护方法的作用。只有当接收者是 self 或与 self 相同的类层次结构时,才能调用它们。保护方法通常在实例方法内部使用。
请参见 http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Protected 您总是可以通过发送方法来规避此行为,例如:
access.send(:retrieve_protected)

尽管这可能被视为不良实践,因为它是有意规避程序员强制实施的访问限制。

0
Ruby中的protected访问控制在初学者看来可能会有些困惑。问题在于你经常会读到在Ruby中,protected方法只能被一个明确的接收者"self"或者"self"类的子实例调用,然而这并不完全正确。
Ruby protected方法的真正规则是,你只能在定义了这些方法的类或子类的上下文中使用一个明确的接收者来调用protected方法。如果你尝试在不是定义这些方法的类或子类的上下文中使用一个明确的接收者来调用protected方法,你将会得到一个错误提示。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接