Today I Learned

hashrocket A Hashrocket project

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
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.