如何使用Ruby的self关键字 [英] How to use Ruby's self keyword

查看:79
本文介绍了如何使用Ruby的self关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我对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屋!

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