在 Ruby 中访问受保护的方法 [英] accessing protected methods in Ruby

查看:60
本文介绍了在 Ruby 中访问受保护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Ruby 中为自己使用访问修饰符.我有:

I am trying to work our for myself access modifiers in Ruby. I have:

class Person
  def initialize (first_name, last_name, age)
        @first_name=first_name
        @last_name=last_name
        @age=age
    end


    def show()
        puts @first_name
        puts @last_name
        puts @age
    end

protected
  def compare(other)
    self.instance_variable_get(:@age)<=>other.instance_variable_get(:@age)
  end

end

p1=Person.new("Some", "Body", "99")
p1.show
puts "\n"

p2=Person.new("Who", "Ever", "21")
p2.show
puts "\n"

p1.compare(p2)

我收到错误为 # (NoMethodError) 调用的受保护方法 `compare'"我试过在课堂内外打电话.我在这里粘贴了无版本.我认为可以在同一类的其他对象上调用受保护的方法.这个错误是什么意思,我将如何在这里正确使用受保护的方法?感谢您的帮助.

I am getting the error "protected method `compare' called for # (NoMethodError)" I have tried calling from within the class and without. I pasted the without version here. I thought that protected methods could be called on other objects of the same class. What does this error mean and how would I properly use a protected method here? Thank you for your help.

推荐答案

您对 protected 可见性的看法是错误的.Ruby 文档 说:

You got the wrong view of the protected visibility. The Ruby doc says:

第二个可见性受到保护.调用受保护方法时发送方必须是接收方的子类,或者接收方必须是发送方的子类.否则将引发 NoMethodError.

The second visibility is protected. When calling a protected method the sender must be a subclass of the receiver or the receiver must be a subclass of the sender. Otherwise a NoMethodError will be raised.

因此可见性的限制适用于发送者,而不是您认为的接收者.

So the restriction of the visibility is applied to the sender, not the receiver as what you thought.

如果要在实例方法之外调用 compare,则需要使用公共可见性.如果可以,您需要删除 protected 修饰符.这是推荐的方式.

If you want to call compare outside of the instance methods, you need to use public visibility. You need to remove the protected modifier if you can. This is the recommended way.

如果代码是固定的并且你不能修改那段代码,你可以使用 Object#send 方法.Object#send 将绕过可见性约束,甚至可以访问私有方法.

If the code is fixed and you cannot modify that piece of code, you can use the Object#send method. Object#send will bypass the visibility constraint and can access even private methods.

p1.send(:compare, p2)

或者您可以重新打开类并更改compare 类的可见性:

Or you can reopen the class and change the visibility of the compare class:

# you code here

# reopen and modify visibility
class Person
  public :compare
end

p1.compare(p2)

这篇关于在 Ruby 中访问受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆