为什么 Ruby 不允许我在私有方法中指定 self 作为接收者?

2023-11-30

Ruby 作为一种面向对象的语言。这意味着无论我发送什么消息,我都严格在类的某个对象/实例上发送它。

Example:

 class Test
   def test1
    puts "I am in test1. A public method"
    self.test2
   end

   def test2
    puts "I am in test2. A public Method"
   end
 end

我调用方法是有道理的test2 on self object

但我不能这样做

  class Test
   def test1
    puts "I am in test1. A public method"
    self.test2 # Don't work
    test2 # works. (where is the object that I am calling this method on?)
   end

   private
   def test2
    puts "I am in test2. A private Method"
   end
 end

When test2 is public method我可以打电话self(公平地说,发送到 self 对象的方法)。但当test2 is private method我不能自己称呼它。那么我发送方法的对象在哪里?


问题

在 Ruby 中,私有方法不能被调用directly有明确的接收者; self 在这里没有得到任何特殊待遇。根据定义,当您调用self.some_method您将 self 指定为显式接收者,因此 Ruby 说“不!”

解决方案

Ruby 有其方法查找规则。可能有更规范的规则来源(除了 Ruby 来源之外),但是这个博客文章在顶部列出了规则:

1) Methods defined in the object’s singleton class (i.e. the object itself)
2) Modules mixed into the singleton class in reverse order of inclusion
3) Methods defined by the object’s class
4) Modules included into the object’s class in reverse order of inclusion
5) Methods defined by the object’s superclass, i.e. inherited methods

换句话说,私有方法首先在 self 中查找,而不需要(或允许)显式接收者。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 Ruby 不允许我在私有方法中指定 self 作为接收者? 的相关文章

随机推荐