Kernel#iterator?
iterator? -> true or false Returns:
Boolean · Updated March 13, 2026 · Kernel Methods blocks iterators checking control-flow
The iterator? method (also known as block_given?) checks whether the current context is being called with a block. It returns true if a block was passed to the current method and is available for yielding.
Basic Usage
def my_method
if iterator?
yield
else
"No block given"
end
end
my_method # => "No block given"
my_method { "block!" } # => "block!"
Practical Examples
Optional Block Handling
def process_items(items)
if iterator?
items.each { |item| yield(item) }
else
items
end
end
# Without block - returns array
result = process_items([1, 2, 3]) # => [1, 2, 3]
# With block - yields each
result = process_items([1, 2, 3]) { |x| x * 2 } # => nil (yields)
Conditional Feature Activation
def find_matches(items)
matches = []
items.each do |item|
if block_given?
matches << item if yield(item)
else
matches << item # Include all if no block
end
end
matches
end
find_matches([1, 2, 3, 4]) # => [1, 2, 3, 4]
find_matches([1, 2, 3, 4]) { |x| x > 2 } # => [3, 4]
API Design
class DataProcessor
def process(data)
return enum_for(:process, data) unless block_given?
data.each do |item|
transformed = yield(item)
store(transformed)
end
end
end
Default Behavior
def greet
if block_given?
yield("World")
else
"Hello, World!"
end
end
greet # => "Hello, World!"
greet { |name| "Hi, #{name}!" } # => "Hi, World!"
Method Names
# Both work identically
iterator?
block_given?
In Conditional Expressions
# Common pattern
def compute
if block_given?
yield
else
default_value
end
end
With enum_for
def each_item(items)
return enum_for(__method__, items) unless block_given?
items.each { |item| yield item }
end
# Now works without block
enum = each_item([1, 2, 3])
puts enum.first # => 1
This method is fundamental to Ruby’s block and iterator system, enabling methods to work both with and without blocks.