Ruby - protected 方法

标签 ruby protected accessor

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

这是为什么?

谢谢。

最佳答案

因为您只能从该对象或该类(或子类)的另一个对象的实例方法直接调用 protected 方法

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

关于Ruby - protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050802/

相关文章:

ruby - 如何操作通过 Nokogiri 解析的 html 页面?

ruby - Ruby 正则表达式是否有像 Perl 中的 "!~"这样的不匹配运算符?

ruby-on-rails - 将 ruby​​ 参数合并到字符串中会引发错误的 url 错误

c++ - 有 friend 看基类吗?

laravel - 为什么我的 Laravel Eloquent 访问器没有出现在响应中?

mysql - 如何让 mysql 将 DateTime 输出为 Julian 日数?

java - 为什么java抽象类中需要Protected构造函数

java - 为什么 protected 变量在类级别可见?

objective-c - 如何从辅助线程安全地访问 NSArray 属性的内容?

c# - 此代码是否在对象创建后不久通过访问器设置值