Ruby tap method

tap method is coded like below

class Object
  def tap
    yield self
    self
  end
end

This method allows us to perform operations on an object within a block and then returns the original object itself.

# Syntax
object.tap { |variable| block }

This method often used when we want to chain multiple method calls on an object while also performing some intermediate operations.

# example
person = Person.new.tap do |p|
  p.name = "John"
  p.age = 30
end

In the above example tap method creates a Person object and then sets name and age attributes and returns this updated person object.

Last updated