from what I understand of the self
keyword, it simply 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 just var_one = method(args)
?
If so then what is the use of self?
One other use of
self
is to declare class methods (similar to static methods in Java).That being said, you could also have used
def foo.bar
instead for the method signature.In most cases
self.foo
is indeed redundant because you can just writefoo
for the same effect, but in this case it is not and theself
is required.var_one = method(args)
will create a local variable calledvar_one
, it will not call any method or do anything else toself
.self.var_one = method(args)
will call the methodvar_one=
onself
with the argumentmethod(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 theself
keyword.here's an example use:
In this case self will help. in most cases self is redundant.
There are several important uses, most of which are basically to disambiguate between instance methods, class methods, and variables.
First, this is the best way to define class methods. IE:
Also, within instance methods self refers to the instance, within class methods it refers to the class, and it can always be used to distinguish from local variables.
So, in the end, you can avoid using
self
in many cases, but it's often helpful to go ahead and use it to make sure that you don't inadvertently create naming conflicts later on. Sometimes those can create bugs that are very hard to find. In the end it's often a matter of personal style.Update: As noted in the comments, one more really important thing:
In a class, if you have a method like this:
And in another method you call:
It isn't going to call your bar= method, it's going to create a local variable bar. So, in this case you use self to tell ruby not to create a local variable, like so:
The same thing applies if you want to take an argument with the name of a method, like so:
If you left off self it would assume you meant the local variable with the same name.
So, in general, self in method names is used to distinguish between class and instance variables, and everywhere else you use it when Ruby needs help distinguishing between method calls and local variables or local variable assignment.
I hope that makes sense!