Featured in
Architecture & Design

Mini-talks: The Machine Intelligence Landscape: A Venture Capital Perspective by David Beyer. The future of global, trustless transactions on the largest graph: blockchain by Olaf Carlson-Wee. Algorithms for Anti-Money Laundering by Richard Minerich.

Featured in
Process & Practices

In-App Subscriptions Made Easy

There are various types of subscriptions: recurring, non-recurring, free-trial periods, various billing cycles and any possible billing variation one can imagine. But with lack of information online, you might discover that mobile subscriptions behave differently from what you expected. This article will make your life somewhat easier when addressing an in-app subscriptions implementation.

Featured in
Operations & Infrastructure

Mini-talks: The Machine Intelligence Landscape: A Venture Capital Perspective by David Beyer. The future of global, trustless transactions on the largest graph: blockchain by Olaf Carlson-Wee. Algorithms for Anti-Money Laundering by Richard Minerich.

Featured in
Enterprise Architecture

Mini-talks: The Machine Intelligence Landscape: A Venture Capital Perspective by David Beyer. The future of global, trustless transactions on the largest graph: blockchain by Olaf Carlson-Wee. Algorithms for Anti-Money Laundering by Richard Minerich.

In Ruby 1.9, the tap method is defined in Object, making it available for every object in Ruby by default. The method takes a Block as argument, which it calls with self as argument - then the object is returned.

The indirection through the tap method seems like a complicated way of doing something with an object. The real benefit of this becomes clear when the object of interest is passed from one method to another without ever being assigned to a variable. This is common whenever methods are chained, particularly if the chain is long. An example: without tap, a temporary variable is needed:

xs = blah.sort.grep( /foo/ )p xs# do whatever we had been doing with the original expression xs.map { |x| x.blah }

In case this code has a bug, tap allows to look at the object at an arbitrary stage (i.e. between every call) by simply inserting a tap block. This is also useful with debugging tools, which often don't support looking at anonymous return values of methods.

It's important to mention that tap is normally about causing some kind of side effect without changing the object (the Block's return value is ignored). However, it is of course possible to modify the object as long as it's mutable.

Users of Rails' ActiveSupport are already familiar with a similar method in the form of the returning method .

Of course, the tap method is not restricted to Ruby 1.9 - Ruby's Open Classes allow to do this on non-1.9 Ruby versions too.