Ruby:使用self关键字从内部调用私有方法

时间:2021-01-20 23:22:24
class MyClass
  def test
    puts my_id
    puts self.my_id
  end

  private

  def my_id
    115
  end
end

m = MyClass.new
m.test

This script results in an output:

此脚本产生一个输出:

115
priv.rb:4:in `test': private method `my_id' called for #<MyClass:0x2a50b68> (NoMethodError)
    from priv.rb:15:in `<main>'

What is the difference between calling methods from inside with self keyword and without it?

使用self关键字调用内部方法与没有它的区别有什么区别?

From my Delphi and C# experience: there was no difference, and self could be used to avoid name conflict with local variable, to denote that I want to call an instance function or refer to instance variable.

从我的Delphi和C#体验:没有区别,self可以用来避免名称与局部变量冲突,表示我想调用实例函数或引用实例变量。

1 个解决方案

#1


2  

In ruby a private method is simply one that cannot be called with an explicit receiver, i.e with anything to the left of the ., no exception is made for self, except in the case of setter methods (methods whose name ends in =)

在ruby中,私有方法只是一个不能用显式接收器调用的方法,即在左边的任何东西都没有。除了在setter方法(名称以=结尾的方法)的情况下,自身没有例外。

To disambiguate a non setter method call you can also use parens, ie

要消除非setter方法调用的歧义,您也可以使用parens,即

my_id()

For a private setter method, i.e if you had

对于私人制定者方法,即如果你有

def my_id=(val)
end

then you can't make ruby parse this as a method call by adding parens. You have to use self.my_id= for ruby to parse this as a method call - this is the exception to "you can't call setter methods with an explicit receiver"

然后你不能让ruby通过添加parens来解析这个方法调用。你必须使用self.my_id = for ruby​​来解析这个方法调用 - 这是“你不能用显式接收器调用setter方法”的例外

#1


2  

In ruby a private method is simply one that cannot be called with an explicit receiver, i.e with anything to the left of the ., no exception is made for self, except in the case of setter methods (methods whose name ends in =)

在ruby中,私有方法只是一个不能用显式接收器调用的方法,即在左边的任何东西都没有。除了在setter方法(名称以=结尾的方法)的情况下,自身没有例外。

To disambiguate a non setter method call you can also use parens, ie

要消除非setter方法调用的歧义,您也可以使用parens,即

my_id()

For a private setter method, i.e if you had

对于私人制定者方法,即如果你有

def my_id=(val)
end

then you can't make ruby parse this as a method call by adding parens. You have to use self.my_id= for ruby to parse this as a method call - this is the exception to "you can't call setter methods with an explicit receiver"

然后你不能让ruby通过添加parens来解析这个方法调用。你必须使用self.my_id = for ruby​​来解析这个方法调用 - 这是“你不能用显式接收器调用setter方法”的例外