Today I Learned

A Hashrocket project

1 post by benlovell @benlovell

Tap that

While Object#tap’s primary usage is to tap into a pure functional styled method chain (get it… tap into?) its usefulness for me comes from returning its receiver. This is fairly typical Ruby code you’re likely to encounter in the wild:

def tiny_rick!
  user = User.new
  user.name = 'Rick'
  user.surname = 'Sanchez'
  user
end

Making use of Object#tap we can golf this down and remove the need for the implicitly returned user:

def tiny_rick!
  User.new.tap do |user|
    user.name = 'Rick'
    user.surname = 'Sanchez'
  end
end

This is all the better when you consider the few lines that make up Object#tap’s implementation:

class Object
  def tap
    yield self
    self
  end
end