为什么 Ruby 不允许我在私有方法中将 self 指定为接收者? [英] Why won't Ruby allow me to specify self as a receiver inside a private method?

查看:40
本文介绍了为什么 Ruby 不允许我在私有方法中将 self 指定为接收者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ruby as an Object Oriented Language. What that means is whatever message I send, I strictly send it on some object/instance of class.

示例:

 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

我在 self 对象上调用方法 test2 是有道理的

makes sense I call method 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

test2public method 我可以在 self 上调用它(很公平,一个方法发送到 self 对象).但是当 test2private method 时,我不能在 self 上调用它.那么我正在发送方法的对象在哪里?

When test2 is public method I can call it on self (fair enough, a method sent to self object). But when test2 is private method I cannot call it on self. So where is the object that I am sending method on?

推荐答案

问题

在 Ruby 中,不能使用显式接收器直接调用私有方法;self 在这里没有得到任何特殊待遇.根据定义,当您调用 self.some_method 时,您将 self 指定为显式接收器,因此 Ruby 说不!"

The Problem

In Ruby, private methods can't be called directly with an explicit receiver; self doesn't get any special treatment here. By definition, when you call self.some_method you are specifying self as the explicit receiver, so Ruby says "No!"

Ruby 有其方法查找的规则.可能有更规范的规则来源(而不是去 Ruby 来源),但是这个 博文 在顶部列出了规则:

Ruby has rules for its method lookups. There may be a more canonical source for the rules (other than going to the Ruby source), but this blog post lays out the rules right at the top:

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 中查找,而不需要(或允许)显式接收器.

In other words, private methods are first looked up in self without requiring (or allowing) an explicit receiver.

这篇关于为什么 Ruby 不允许我在私有方法中将 self 指定为接收者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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