Simplify your Ruby code with tap

I only recently discovered the tap method, which was added in Ruby 1.9. Basically, if you ever find yourself writing code like this:

def user_mapping
  mapping = {}
  User.all.each do |user|
    mapping[user.email] = user
  end
  mapping
end

You can now simplify this code using the tap method:

def user_mapping
  {}.tap do |mapping|
    User.all.each do |user|
      mapping[user.email] = user
    end
  end
end

Basically tap allows us to access any variable in a block, which then returns the original variable.

Another nice use case is when initializing a new object:

def initialize_user(params)
  User.new(params).tap |user|
    user.created_at = Time.now
  end
end

This saves us having to first assign the object of interest to a local variable simply to be able to reference it.

The implementation for tap looks something like this:

class Object
  def tap
    yield self
    self
   end
end 

Which means it’s available on any object. Happy coding.