【问题标题】:Is it possible to access the protected methods outside the class - ruby是否可以访问类之外的受保护方法 - ruby
【发布时间】:2018-12-10 08:01:01
【问题描述】:
class User    
  def say_secret_with_self
    self.secret
  end

  protected

  def secret
    "secret"
  end
end

u = User.new
p u.say_secret_with_self   # => "secret"

我听说受保护的方法只能被继承的成员访问。但以上在红宝石中是可能的。代码正确吗?

【问题讨论】:

  • self.secret 可以简化为secret,因为self 是隐式接收者。但是,如果secret 是private,则不能使用显式接收器,即使self;你必须写secret。
  • “继承成员”应该是什么意思?另外,如果可能的话,它是一个正确的代码。
  • “是否可以在类外访问受保护的方法”——你不能从类外访问protected方法secret班级。您访问 public 方法say_secret_with_self。受保护的方法是从在类中调用的。

标签: ruby


【解决方案1】:

方法secret 仍然受到保护。你不能从你的类(或继承的类)之外调用它。但是您可以从say_secret_with_self 调用它,因为它仍然与secret 在同一类中

【讨论】:

    【解决方案2】:

    是的,它是正确的代码。类的实例能够调用 self 方法,即使它们是 protected。 protected/private 方法对外部隐藏,但对内部隐藏。

    【讨论】:

      猜你喜欢
      • 2014-10-31
      • 2014-11-18
      • 2020-07-26
      • 2013-04-06
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2011-10-26
      • 2014-05-01
      相关资源
      最近更新 更多