yield (Ruby)

yield calls the block that was passed to the current method, optionally passing it arguments. It's how a method hands control to its block, enabling custom iteration and callback patterns.

Ruby

When a method is called with a block, yield inside that method runs the block. You can pass values to it (yield item) which become the block's parameters, and the block's result becomes yield's return value. Use block_given? to check whether a block was supplied before yielding.

yield lets you write your own iterators and 'wrapper' methods. A method can yield multiple times (the basis of each-style loops) or wrap setup/teardown around a yield (the open/use/close pattern).

yield works with the implicit block. If you want to store, pass on, or inspect the block as an object, capture it explicitly with an &block parameter, which turns it into a Proc you can call with .call.

Syntax

def my_method
  yield(value) if block_given?
end

Examples

Ruby

def twice
  yield 1
  yield 2
end

twice { |n| puts "got #{n}" }

Output:

got 1
got 2

Learn it in a lesson

See also

Back to the Dictionary