如何使用Ruby的self关键字 [英] How to use Ruby's self keyword
问题描述
据我对self
的了解,它是指该类的当前实例.
这不是始终都是默认行为吗?例如,不是
self.var_one = method(args)
等同于
var_one = method(args)
如果是,self
有什么用?
在大多数情况下,self.foo
确实是多余的,因为您可以只写foo
以获得相同的效果,但是在这种情况下,它不是,并且
var_one = method(args)
将创建一个名为var_one
的局部变量,它将不会调用任何方法或对self
做其他任何事情.
self.var_one = method(args)
将使用参数method(args)
调用self
上的方法var_one=
.
另一种不可选使用self
的情况是,如果您想将其作为方法的参数传递给some_method(self)
,那么-如果没有self
关键字就无法做到这一点. /p>
From what I understand about self
, it refers to the current instance of the class.
Isn't this the default behaviour at all times anyways? For example, isn't
self.var_one = method(args)
equivalent to
var_one = method(args)
If so, what is the use of self
?
In most cases self.foo
is indeed redundant because you can just write foo
for the same effect, but in this case it is not and the self
is required.
var_one = method(args)
will create a local variable called var_one
, it will not call any method or do anything else to self
.
self.var_one = method(args)
will call the method var_one=
on self
with the argument method(args)
.
Another case where the use of self
is non-optional would be if you want to pass it as an argument to a method, i.e. some_method(self)
- you can't do that without the self
keyword.
这篇关于如何使用Ruby的self关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!