๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Ruby Blocks and Yield

A block is a chunk of code passed along with a method call. The word yield inside a method runs the block that came with the call.

Yield runs the block

The announce method prints a line, yields, and prints another line. The block from the call runs between the two lines.

def announce
  puts "Starting"
  yield
  puts "Finished"
end

announce { puts "The block ran" }

Yield twice runs the block twice

The repeat method yields two times. The block adds one to step and prints it on each run, so the printed lines count 1 then 2.

def repeat
  yield
  yield
end

step = 0
repeat do
  step += 1
  puts step
end

Yield passing a value

The roll_call method yields with a name each time. The block parameter name receives the value, and the block prints a line for each name.

def roll_call
  yield "Ana"
  yield "Ben"
end

roll_call { |name| puts "Here is #{name}" }

Example

def each_step
  yield "wash"
  yield "rinse"
  yield "dry"
end

each_step { |step| puts "Now #{step}" }

Key points

  • A one-line block is written in braces.
  • A longer block is written between do and end.
  • The word yield runs the block that came with the call.
  • Each yield in a method runs the block one more time.
  • Yield can pass a value into a block parameter.
  • A block parameter is written between two | marks.
  • A method can test for a block with the word block_given?.

In this example, the each_step method yields three times, and each yield passes one word. The block receives each word in its step parameter. The block prints one line for each word, in order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does yield do inside a method?