如何使用Ruby“自我"关键词 [英] How to use the Ruby "self" keyword
问题描述
我无法理解 self
关键字.
I'm having trouble understanding the self
keyword.
我理解它是如何用来区分实例方法和类方法的,但是当它在方法内部使用时呢?
I understand how it's used to distinguish between instance methods and class methods but what about when it's used from inside a method?
类似于:
def self.name
self.name = "TEXT"
end
或
def name2
self.name = "TEXT2"
end
或
class Array
def iterate!(&code)
self.each_with_index do |n, i|
self[i] = code.call(n)
end
end
end
推荐答案
通常,作为接收者的 self
可以省略,在这种情况下,通常最好这样做.但是,在某些情况下,省略 self
会使代码具有其他含义.
Usually, self
as a receiver can be omitted, and in such cases, it is usually preferable to do so. However, there are a few cases when omitting self
make the code mean something else.
一种这样的情况,就像在您的示例
self.name = ...
中一样,使用 setter 方法.Ruby 的语法在方法和变量调用之间存在歧义,当可以解释为变量或方法的东西后跟=
时,将其解释为局部变量赋值具有优先权.
One such case is, as in your example
self.name = ...
, using a setter method. Ruby's syntax is ambiguous between method and variable call, and when something that can be interpreted either as a variable or a method is followed by=
, its interpretation as a local variable assignment has priority.
另一种情况是当您想要调用方法 class
时.还有关键字class
,对class
的解释是关键字优先于方法.
Another case is when you want to call the method class
. There is also the keyword class
, and interpretation of class
as the keyword has priority over it as the method.
还有一种情况是当您想使用方法 []
时.这种表示法也用于数组字面量,将其解释为数组优先于作为方法的解释.
Still another case is when you want to use the method []
. This notation is also used for array literal, and interpretation of it as an array has priority over it as a method.
在每种情况下,您都必须使表达式明确地成为方法调用.一种方法是显式编写接收器,即使它是 self
.另一种方式是在方法后写()
.
In each of these cases, you have to make the expression be unamgiguously a method call. One way is to explicitly write the receiver even when it is self
. The other way is to write ()
after the method.
关于您的示例 self.each_with_index ...
,self
可以省略,不建议这样做.
Regarding your example self.each_with_index ...
, the self
can be omitted, and not doing so is not a recommended practice.
这篇关于如何使用Ruby“自我"关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!