What is a block in Ruby, and what does yield do?
A block is a chunk of code you hand to a method, written between do and end or between braces. Inside the method, the word yield runs that chunk, once for each yield, and passes it any values you give. The method decides when and how often the block runs; the block decides what to do with each value.
Cite
Poignant Guide Ruby Q&A, "What is a block in Ruby, and what does yield do?", https://poignantguide.net/answers/read/what-is-a-block-in-ruby-and-what-does-yield-do/, accessed 2026-11-16.- Odile MarchettiStaffStaff: Ruby basics, objects and the Poignant Guide ·
A minimal example
Save this as
block.rband run it withruby block.rb:def greet puts "before" yield puts "after" end greet { puts "hello" } # => before # => hello # => afterA method is a named piece of code, and
defstarts one. Heregreetprints a word, runs your block withyield, then prints another word. The part in braces after the call is the block. Ruby pausesgreetat theyieldline, runsputs "hello", and then continues.You can yield as many times as you like, and you can pass values. Values go between vertical bars at the start of the block, and those names are the block parameters:
def with_name yield "Ada" end with_name { |name| puts "Hello, #{name}" } # => Hello, Ada def twice yield yield end twice { puts "hi" } # => hi # => hiWhy it works
The Ruby documentation on calling methods says the block argument sends a closure from the calling scope to the method, and that it is always the last thing sent. A closure is code that remembers the variables around the place where you wrote it. You can see that here:
total = 10 [1, 2, 3].each { |n| total += n } p total # => 16The block changed
total, even thougheachis a method written somewhere else, because the block carries the surrounding variables with it.The documentation on defining methods adds that if you only call the block and do not otherwise handle it, using
yieldwithout a named block parameter is preferred. Methods likeeach,mapandselectare written this way: each gives your block one item at a time, and what the block does with the item is up to you.You can write one yourself:
def my_each(items) i = 0 while i < items.length yield items[i] i += 1 end end my_each(%w[a b]) { |x| puts x } # => a # => bA yield also returns a value: whatever the last line of the block gives back.
def square_all(numbers) result = [] numbers.each { |n| result << yield(n) } result end p square_all([1, 2, 3]) { |n| n * n } # => [1, 4, 9]Braces or do and end?
Both create a block. The convention is braces for one line and do...end for several lines. The calling-methods page also explains a real difference: do...end has lower precedence than braces. Precedence means which call grabs the block first.
puts [1, 2, 3].map { |n| n * 2 } # => 2 # => 4 # => 6 puts [1, 2, 3].map do |n| n * 2 end # prints an Enumerator object, not the doubled numbersIn the second version the block goes to
puts, not tomap, becausedobinds to the outermost call. Use braces here, or save the result in a variable first.When no block is given
If a method yields and the caller passes no block, Ruby raises an error. The Kernel documentation lists
block_given?, which returns true if a block was passed to the calling method:def maybe if block_given? yield 1 else puts "no block" end end maybe # => no block maybe { |x| puts x } # => 1Without the check, calling
yieldwith no block ends inLocalJumpErrorwith the messageno block given (yield).Mistakes beginners make
- Expecting each to return the new values.
eachreturns the original array. If you want a new array, you wantmap, which I cover in a later answer on the difference between map, each and select. - Yielding when the method was never given a block. Add
block_given?or pass a block. - Wrong parameter count. A block with
|a, b|getsnilforbif you yield one value. The blocks are forgiving about this, which can hide a bug. - Using do...end inside puts. See the precedence example above.
Check this in order
- Is there a
yieldinside the method you are calling? If not, the block is quietly ignored. - Does the call end with
{ ... }ordo ... enddirectly after the method name and arguments? - Do the names between
| |match the number of values the method yields? - Are you printing the return value of
eachand hoping for the block's results? Switch tomap. - Did a
do...endblock end up attached toputsor another outer method? Switch to braces.
The same idea is the backbone of Chapter 3 and Chapter 4 of the guide, so read them with irb open. A block with
&:upcaseas shorthand uses a symbol; What is a symbol in Ruby, and when should I use one instead of a string? covers that side. To see exactly whatpshows for these results, read What is the difference between puts, print and p in Ruby?.Checked on 12 November 2026.
- Expecting each to return the new values.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.