2011-08-13 157 views
3

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

这是为什么?

谢谢。

+1

你预计会发生什么? –

回答

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

这是受保护的方法是所有关于Ruby方法。只有在接收者为self或与self具有相同的等级层级时,才能调用它们。受保护的方法通常在实例方法的内部使用。

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

您可以随时通过发送方法,例如规避这种行为

access.send(:retrieve_protected) 

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

0

Ruby中受保护的访问控制起初可能会让人困惑。问题在于,你经常会阅读Ruby中的受保护方法,只能通过显式的“self”接收器或“self”类的子实例来调用,无论该类是什么。这并不完全正确。

Ruby受保护方法的实际处理是,您只能在“上下文”中使用显式接收器调用受保护的方法,该方法是定义这些方法的类或子类的实例。如果尝试用一个显式的接收器来调用一个受保护的方法,并且在上下文中不是你定义方法的类或子类时,你会得到一个错误。