Ruby Block Arguments
A method can hand a value to its block with yield. The block receives that value as its block argument.
Yield hands a value to the block
announce yields the word ready. The block names it word and prints it.
def announce
yield "ready"
end
announce do |word|
puts word
endTwo yields, two runs
count_up yields 1 and then 2. The block runs once for each yield.
def count_up
yield 1
yield 2
end
count_up do |n|
puts "Count #{n}"
endThe block last value as the answer
double_it yields 6 and keeps the value the block makes. The block doubles it, and the method prints that result.
def double_it
result = yield 6
puts result
end
double_it do |n|
n * 2
endAn optional block, guarded
greet yields only when a block came with the call. The second call passes no block, so the guard line prints instead.
def greet
if block_given?
yield
else
puts "No block given"
end
end
greet do
puts "Hello from the block"
end
greetExample
def serve_customers
yield "Ana"
yield "Ben"
end
serve_customers do |name|
puts "Serving #{name}"
endKey points
- yield runs the block that came with the method call.
- yield followed by a value hands that value to the block.
- The block names the value it receives between two pipe characters.
- A method can use the last value its block makes as its own result.
- Two yield lines run the block twice, once per line.
- block_given? answers true when a block came with the call.
In this example, serve_customers yields two names, one after the other. The block runs once per yield and names each value name. The two serving lines print in the order the method yields them.
Note
A block runs only when the method reaches a yield line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does yield 5 hand to the block?