Ankit Soni Ankit Soni - 1 year ago 112
Ruby Question

Use of ruby self keyword?

from what I understand of the

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?

Answer Source

In most cases 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download