Object#tap
obj.tap { |x| block } -> obj Returns:
Object · Updated March 13, 2026 · Core Classes blocks debugging method-chaining
tap yields the receiver to a block and then returns the object itself. This simple method is incredibly useful for debugging and method chaining without creating intermediate variables.
Syntax
obj.tap { |x| block }
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | Block | required | A block that receives the object as its parameter |
Examples
Basic usage
# tap returns the object itself
message = "Hello, World!"
message.tap { |m| puts m }
# Hello, World!
# => "Hello, World!"
Debugging method chains
# tap shines when debugging pipelines
result = [1, 2, 3, 4, 5]
.map { |x| x * 2 }
.tap { |arr| puts "After map: #{arr.inspect}" }
.select { |x| x > 4 }
.tap { |arr| puts "After select: #{arr.inspect}" }
# After map: [2, 4, 6, 8, 10]
# After select: [6, 8, 10]
# => [6, 8, 10]
Setting up objects
# Configure an object in a single expression
config = {}.tap do |h|
h[:host] = "localhost"
h[:port] = 3000
h[:env] = "development"
end
# => { host: "localhost", port: 3000, env: "development" }
Common Patterns
Debugging in pipelines
tap shines when you need to inspect values mid-chain without disrupting the flow:
# Inspect without breaking the chain
data = [1, 2, 3]
.map { |x| x ** 2 }
.tap { |arr| puts "Squared: #{arr}" }
.sum
# Squared: [1, 4, 9]
# => 14
Initializing objects
class Connection
attr_accessor :host, :port, :ssl
end
conn = Connection.new.tap do |c|
c.host = "localhost"
c.port = 3000
c.ssl = true
end