【问题标题】:Ruby - Protected methodRuby - 受保护的方法
【发布时间】:2011-10-26 10:04:58
【问题描述】:

我有以下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)

为什么会这样?

谢谢。

【问题讨论】:

  • 你预计会发生什么?

标签: ruby protected accessor


【解决方案1】:

因为你只能直接从这个对象的within实例方法调用受保护的方法,或者这个类(或子类)的另一个对象

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...

【讨论】:

    【解决方案2】:

    这就是 Ruby 中受保护的方法的全部意义所在。只有当接收者是self 或与self 具有相同的类层次结构时才能调用它们。受保护的方法通常在内部实​​例方法中使用。

    http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Protected

    您始终可以通过发送方法来规避这种行为,例如

    access.send(:retrieve_protected)
    

    虽然这可能被认为是不好的做法,因为它故意规避程序员施加的访问限制。

    【讨论】:

      【解决方案3】:

      Ruby 中的受保护访问控制起初可能会让人感到困惑。问题是您经常会看到 Ruby 中的受保护方法只能由“self”的显式接收者或“self”类的子实例调用,无论该类可能是什么。这并不完全正确。

      与 Ruby 保护方法的真正区别在于,您只能在“上下文”中调用具有显式接收器的受保护方法,以及您在其中定义了这些方法的类或子类的实例。如果您尝试使用显式接收器调用受保护的方法,其上下文不是您定义方法的类或子类,您将收到错误。

      【讨论】:

        猜你喜欢
        • 2012-01-09
        • 2014-10-31
        • 2020-03-31
        • 2016-02-19
        • 2012-06-23
        • 2011-05-18
        • 2012-01-08
        • 2020-07-26
        • 2010-10-30
        相关资源
        最近更新 更多