I'm hoping someone can explain why I get the same behavior from both of these methods and what that means for when to or not to use self.
def my_instance_method(arg)
'execute some code' if another_instance_method_of_same_class?(arg)
end
seems to behave exactly the same as
def my_instance_method(arg)
'execute some code' if self.another_instance_method_of_same_class?(arg)
end
My apologies if my search skills aren't up to par but I couldn't find the exact answer to this question, just explanations of what self does (which made me think I should need it). I'm using the latest version of Ruby. Thank you.
There are a few differences between
self.foo(...)
andfoo(...)
, but they're mostly equivalent.Privacy
private
methods can only be called viafoo
directly, and never with an explicit receiver. So iffoo
is markedprivate
, then you have to call it withoutself
.Shadowing
If you have a local variable called
foo
in the current function, then writingfoo
without arguments will reference the local variable insteadAssignment
If the method you're talking about is an assignment method (i.e. ends in
=
), then it must always be called with an explicit receiver