Hacker News new | ask | show | jobs
by danso 5192 days ago
>> Using a method that is called on self in a class, don’t use self.method_name when just plain method_name will do. (loc. 1500)

I don't have the book in front of me so I don't know what the context is, but this strikes me as something as barely worth highlighting, other than to show that you grok Ruby's method chain.

Some programmers would argue that using self.method_name helps clear up ambiguity to humans who read the code, even if it is equivalent to method_name

4 comments

Especially because some bare method calls will produce syntax errors ('class' being the obvious example).

I think there's no good rule of thumb to be had here; use whichever style makes the code clearer.

That's exactly the rule of thumb that makes for good Ruby: use whatever style makes the code clearest. Over the last ten years, my Ruby has evolved as I've come to understand this (and it's affected the code I write in every other programming language I know, including bash scripts).

At times, this means I have to skip a one-liner because it's not as clear as expanding it out; at other times, it means using a one-liner because it's clearer than an expanded form. Sometimes it means using #length on a String or Array, sometimes it means using #size. They do the same thing (much to the annoyance of some folks), but the fact that both work means I can think about how my code reads.

What's missing in the other comments is that you can't call private methods with an explicit receiver, for example my_object.private_meth or even self.private_meth. On the other hand, public and protected methods can be called on self.

See this blog post for more info: http://www.skorks.com/2010/04/ruby-access-control-are-privat...

Some programmers would argue that using self.method_name helps clear up ambiguity to humans who read the code, even if it is equivalent to method_name

This is the reason I highlighted it. I had heard both sides of the argument from peers and was a little conflicted myself. Russ is simply the highest authority I've encountered to have an opinion on it.

It fits in the Ruby philosophy and coding style to leave the `self.' out. But it might not be so evident for non-rubists.

Actually, new rubists might not even know that you can leave it out. In php you are required to use `$this->' for instance members.