Additional thoughts on `self`
The style guide currently takes a hard-line position on self that it shouldn't be used unless you're doing an attribute assignment. I would argue that this is actually an over-simplification.
Consider:
selfneeds to be used with operators (e.g.self + other,self - [:x, :y], depends on the domain). In fact, RuboCop even calls this out explicitly as a case whereselfis not penalized because it's required.- clarity in "spaceship operator" comparisons (i.e. sorting methods).
For example:
class Student
def <=>(other)
self.name <=> other.name
end
end
In this case, self helps draw a distinction between a value in the current instance and the other instance. It balances out the comparison.
@GuyPaddock Good points. I completely agree we can improve the wording and extend the current rule to be more informative. PRs welcome!
Should the following change do it?
- Avoid `self` where not required.
+ Avoid calling methods on explicit `self` where not required.
+ # ok - `self`'s value is referred, `self` is not used to call a method upon
+ def ^(power)
+ self ** power
+ end
I'm open to ideas for a better code example that would use a reference to self. Please keep in mind that self + other is still a method call, just an implicit one (self.+(other)).
I disagree in part of explicitly sending messages to literal self improves clarity. <=> is a regular instance method, and the same rules should apply.
Do you mind if we just add a clarification, and not relax the guideline for <=>?
On a side note, in Ruby 2.7 it become possible to call private methods on explicit literal self just like with no receiver, see https://bugs.ruby-lang.org/issues/11297