Ruby 3 · Blocks, classes and pattern matching

Write a method that takes a block

yield runs the block the caller supplied. Pass data to the block as arguments.

def repeat(times)
  times.times { |i| yield i + 1 }
end

repeat(3) { |n| puts "round #{n}" }

Official Ruby 3 documentation

More blocks, classes and pattern matching commands

All blocks, classes and pattern matching commands · Ruby 3 cheatsheet

Was this page helpful?