Code & Clay – Notes to self. Mainly Ruby/Rails.

What does the tap method do in Ruby?

Object#tap yields the object it is called upon to a block but the resulting value is the value of the object (not the value of the block). For example:

> 1.tap { |obj| puts obj * 2 }
=> 1

The value 1 is passed to the block where we output the result of obj * 2 (2). However, the value of the expression is the value of the object: 1.

Say we have a User class:

class User
  attr_accessor :name

To create a new user, we might do something like this:

def user
  new_user = = @name

The return value of the above method is a new user object with its name assigned to the value of @name.

You can see we have to create the temporary variable new_user to hold the value of the new user in order for us to assign its name. We then return the value of the temporary variable.

#tap removes the need for the temporary variable.

def user { |obj| = @name }

In the above example, we call #tap on the newly instantiated user object. Inside the block, we assign a name to the new user. The resulting value is the newly instantiated user object with its name assigned the value of @name.

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6