Lets Tap Together
A few weeks ago Gregory Brown wrote a nice blog post which initiated an interesting discussion about the Object#tap method. The method is part of the Ruby core since version 1.9 but is also available in later versions of 1.8.7. The probably first usage of this method was for debugging.
But this post is about another approach. When you have to iterate over an array to save some information in a new array or hash you may write like I did already many times in my Ruby on Rails applications.
def foo array = [] [1, 2, 3].each do |number| array << number.next end array end
At first you initialize an empty array. Then you iterate over an another array or hash to store some awesome information in that new array. And at the end of the method you need to return the array.
The next example comes to the same result but it uses the tap method.
def bar [].tap do |array| [1, 2, 3].each do |number| array << number.next end end end
I agree with you if you think the first example is more readable and easier to understand. But when I used code like the first example, I often thought: “Is it really necessary to initialize and return that array?”. Like you can see, it’s not but it’s more readable.