Blocks

Build a big expertise of Ruby –
One small block of knowledge at a time.


A Clean Way to Chain Object Modifications

The tap method yields an object to a block and returns the object itself. It's perfect for performing operations on an object while maintaining a clean chain.

# Without tap
user = User.new
user.name = "John"
user.save
return user

# With tap
User.new.tap do |user|
  user.name = "John"
  user.save
end

Great for object initialization, debugging method chains, and keeping your code DRY. Use it when you need to perform multiple operations on an object while maintaining method chaining.