Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 13 of 23 · Ruby 3.4

Pass an action with a block

Attach a block to a method call and follow how yield runs it.

Learn

A block is code attached to a method call, written with do ... end or braces. The method decides when to run that code. In a method definition, yield runs the attached block and then continues with the next expression.

yield can pass values to the block. Names between vertical bars, such as |message|, receive those values as block parameters. The block returns the value of its final expression to yield, so the method can use it.

The methods here require a block because they call yield without checking whether one was supplied. Keep the method definition, call and attached block together while tracing the flow.

Example

def announce
  puts "Before action"
  yield
  puts "After action"
end

announce do
  puts "Pack the order"
end

Experiment

  • Predict the line. Change the block to print a different sentence using the supplied customer name.

  • Predict the printed price. Change the block to subtract 3 instead and follow the value returned to yield.

  • Predict the order of the lines. Add a line before the first yield and check how many times that added line runs.

Explore the official manual

Ruby 3.4.1 · Example

Ready to run

Output

Run the code to see what happens.