Connecting to LinkedIn...

Ruby Tap Returning

over 4 years ago by


Recently someone pointed out to me a YouTube guide illustrating use of the Ruby #tap method. I watched and recognised the intent, but thought “I don’t know when I would need such a construct”.

A matter of days later I’m upgrading an app and fall foul of an unknown method #returning used in an old plugin.

The obvious first port of call is Google or Stack Overflow to see what everyone else has done with this – surely I’m not the first? Lots of entries confirm that the returning method was deprecated and then removed, but none show the modern replacement.

Examining the examples of usage of returning I’m reminded of something… The whole point of the method is to do some work on an object in a block and then to make sure that the block is returned rather than the result of the last assignment within the block… isn’t that what #tap does?

Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

Sure enough, on revisiting both set of docs and a couple of on-line guides I’m certain that tap is a direct replacement for returning – it just looks more Ruby-like.

It’s common in lots of languages to need to declare an object, do some work on or relating to it and then to continue with that object in focus.

One popular pattern within Ruby is

def example_method
  example_var =*args)
  return example_var

Without the final return example_var the result of the .save! method would be returned: true or false.

To avoid the need to explicitly return the object we had the returning method.

returning some_object do |the_object|
  act_on the_object
end # returns the_object as some_object

Now we have tap to do the same thing but looking a little more Ruby-like.

some_object.tap |the_object|
  act_on the_object
end # returns the_object as some_object

I wonder why there’s nothing to say tap is a direct replacement for the deprecated returning?

I need to apologise for the picture. I couldn’t think what image would be representative of the content of this blog entry, and my initial vague search brought up Dorothy’s Ruby slippers, with which she could tap her heels as a way of returning to Kansas.