#tap Refactor


A few weeks ago I was informed by a coworker of the magic you can do with #tap

Here’s an example of code that tends to show up a lot in our codebase:

arr = []
items.each do |item|
  # ...
  arr << item
end
arr

The need for an explicit return is bothersome to me, it would be nice if we could do this in one block.

That’s where #tap comes in. Here’s the same example using tap:

[].tap do |arr|
  items.each do |item|
    # ...
    arr << item
  end
end

It may not seem like a major improvement, and alone it is not, but it does make it a bit nicer if we move this snippet. We won’t have to worry about declaring a new variable or adding an explicit return at the end.