Last Updated: February 25, 2016
· siefca

Make tap{} return anything

If you are a fan of tap method you probably used it to make compact assignments like that:

def sources
  @sources ||= [].tap do |s|
    s << "source1"
    s << "source2"

or to make nice looking one-liners of chained methods operating on and returning the original object:

[1,2,3,4,5].tap{ |a| a.delete(2) }.reverse

Besides that tap may be helpful in creating flow control statements that return anything you want instead of an object that you tapped into. That allows you to create one-liners that generate new objects based on the original one:

[1,2,3,4].tap{ |a| break a.count > 1 ? [a.first] : a }

The magic keyword here is the break. If you pass some object to it then the result of calling a tap will be that object.

1 Response
Add your response

One of the things I like about Ruby is how elegantly code can be written, specifically with regards to it reading like a sentence. I would steer clear of this personally, as it's pretty confusing not only for the lack of readability of the line in general, but also because it is contradicts the expected patterns and usage that come with the tap method.

over 1 year ago ·