Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Yield

def run
  puts "before"
  yield
  puts "after"
end

run {
  puts "in block"
}

run do
  puts "in do-end"
end
  • Optionally you can add a &anything if you think that makes the code more readable, but the important part is having yield in the code.
def run(&block)
  puts "before"
  yield
  puts "after"
end

run {
  puts "in block"
}
  • You can call yield more than once inside the function and the block will be executed for every yield.
def run
  puts "before"
  yield
  puts "middle"
  yield
  puts "after"
end

run {
  puts "in block"
}
puts "----"
run do
  puts "in do-end"
end