Skip to content
Poignant Guide Ruby Q&A

What is a block in Ruby, and what does yield do?

Staff answerWritten by Odile Marchetti · Blocks, procs and iterators0 replies

Short answer

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.

Written by Odile Marchetti · Staff: Ruby basics, objects and the Poignant Guide ·
CitePoignant 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.
  1. Staff: Ruby basics, objects and the Poignant Guide ·

    A minimal example

    Save this as block.rb and run it with ruby block.rb:

    def greet
      puts "before"
      yield
      puts "after"
    end
    
    greet { puts "hello" }
    # => before
    # => hello
    # => after
    

    A method is a named piece of code, and def starts one. Here greet prints a word, runs your block with yield, then prints another word. The part in braces after the call is the block. Ruby pauses greet at the yield line, runs puts "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
    # => hi
    

    Why 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   # => 16
    

    The block changed total, even though each is 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 yield without a named block parameter is preferred. Methods like each, map and select are 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
    # => b
    

    A 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 numbers
    

    In the second version the block goes to puts, not to map, because do binds 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 }     # => 1
    

    Without the check, calling yield with no block ends in LocalJumpError with the message no block given (yield).

    Mistakes beginners make

    1. Expecting each to return the new values. each returns the original array. If you want a new array, you want map, which I cover in a later answer on the difference between map, each and select.
    2. Yielding when the method was never given a block. Add block_given? or pass a block.
    3. Wrong parameter count. A block with |a, b| gets nil for b if you yield one value. The blocks are forgiving about this, which can hide a bug.
    4. Using do...end inside puts. See the precedence example above.

    Check this in order

    1. Is there a yield inside the method you are calling? If not, the block is quietly ignored.
    2. Does the call end with { ... } or do ... end directly after the method name and arguments?
    3. Do the names between | | match the number of values the method yields?
    4. Are you printing the return value of each and hoping for the block's results? Switch to map.
    5. Did a do...end block end up attached to puts or 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 &:upcase as 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 what p shows for these results, read What is the difference between puts, print and p in Ruby?.

    Checked on 12 November 2026.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

Poignant Guide Ruby Q&A. Questions and answers on learning Ruby and programming: syntax, blocks, objects, gems, Rails, debugging and reading the Poignant Guide.