Kernel#block_given?
block_given? -> true or false Returns:
true or false · Updated March 13, 2026 · Core Classes blocks control-flow kernel
block_given? (also available as iterator?) is a Kernel method that checks whether the current method was called with a block. It returns true if a block is associated with the current call, and false otherwise. This method is essential for writing flexible methods that can behave differently depending on whether a caller provides a block.
Syntax
block_given?
Parameters
This method takes no parameters.
Examples
Basic usage
def greet
if block_given?
yield
else
puts "Hello!"
end
end
greet { puts "Hello from the block!" }
# Hello from the block!
greet
# Hello!
Checking for a block before yielding
def process_items(items)
if block_given?
items.map { |item| yield item }
else
items
end
end
result = process_items([1, 2, 3]) { |n| n * 2 }
# => [2, 4, 6]
result = process_items([1, 2, 3])
# => [1, 2, 3]
Common Patterns
Optional block with custom behavior
def configure
config = { timeout: 30, retries: 3 }
if block_given?
yield(config)
end
config
end
config = configure do |c|
c[:timeout] = 60
c[:retries] = 5
end
# => { timeout: 60, retries: 3 }
config = configure
# => { timeout: 30, retries: 3 }
Building strings conditionally
def build_message(base)
message = base
if block_given?
message = yield(message)
end
message
end
build_message("Hello") { |m| m + ", World!" }
# => "Hello, World!"
build_message("Hello")
# => "Hello"
Errors
Calling yield without a block raises a LocalJumpError. Always check block_given? before using yield to prevent this error.
def unsafe
yield # Raises LocalJumpError if no block given
end
def safe
yield if block_given? # Safe
end