Everyone loves blocks in Ruby because you no longer have to write ‘for’ or ‘while’ loops.
people.each do |each| puts each.name end
That’s nice and short. And the collection is responsible for looping over its elements which makes sense because its their elements.
So various Enumerable (the module that’s included in Array and Hash) methods expect a block and in return pass each of their elements to the block one at a time. In the above code I named that variable each.
I use each after the master Kent Beck created the pattern ‘Simple Enumeration Pattern’. In it he states:
It is tempting to try to pack as much meaning as possible into every name. Certainly, classes, instance variables, and messages deserve careful attention. Each of these elements can communicate volumes about your intent as you program.
Some variables just don’t deserve such attention. Variables that are always used the same way, where their meaning can be easily understood from context, call for consistency over creativity. The effort to carefully name such variables is wasted, because no non-obvious information is communicated to the program. They may even be counter-productive, if the reader tries to impute meaning to the variable that isn’t there.
Therefore, call the parameter each. If you have nested enumeration blocks, append a descriptive word to all parameter names.
Beck basically says use each as the variable name unless you have a situation where you can’t use it like:
posts.each do |post| post.comments.each do |comment| puts comment.body end end
In response to the above code he states:
Nested blocks that iterate over unlike collections should probably be factored with Composed Method.
Composed Method is another of his patterns that turns a method into nothing but calls to other methods. So he’s saying if you’ve got nested blocks and can’t use each, then you should refactor them out into their own methods, then you can use each again.
I agree with Beck. Using each is a simple standard that takes no time using and understanding each time you see it.