Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 134 ยท Methods and Blocks

Blocks

Learn Ruby blocks from scratch - yield, block_given?, passing arguments, the &block parameter, block-local variables and how return, break and next behave.

A block is a chunk of code that you hand to a method. The method decides when, how often and with which arguments to run it. You have already used blocks: 3.times { puts "hi" } passes the code between the braces to times, and times runs it three times. Blocks are the single most characteristic feature of Ruby. Almost every loop, every file operation that cleans up after itself, every "do something for each element" call and every configuration DSL is built on them.

This lesson shows both sides: how to call a method with a block, and how to write a method that accepts one. You will learn yield, block_given?, the &block parameter, block-local variables, and the three ways a block can end early (next, break and return), which behave differently and trip up many people. Procs and Lambdas then turns a block into an object you can store.

Calling a method with a block

A block is written either with braces or with do ... end. The two forms mean the same thing, but they bind differently, and the community convention is: braces for one-liners, do ... end for multi-line blocks.

Ruby Two ways to write a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The names between the vertical bars are the block parameters. The method passes values to them, one per argument it yields. A block never gets its own name: it is simply "the block" of that method call, and a call can have at most one.

Braces bind tighter than do ... end. In puts [1, 2, 3].map do |n| n * 2 end the do block goes to puts, not to map, so you see an Enumerator instead of the doubled numbers. Use braces when the result of the call is an argument to something else.

Writing a method that yields

The keyword yield runs the block that was passed to the current method. Anything you write after yield becomes an argument for the block.

Ruby yield runs the caller's code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is inversion of control in its friendliest form. twice owns the structure (what happens before, how often, what happens after); the caller supplies the one interesting part. Compare that with a plain function that returns a list and makes the caller write the loop.

What yield returns

yield is an expression. Its value is whatever the block's last expression evaluates to. That is how map, select and sum get answers from your code.

Ruby The value of the block comes back through yield

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You have just reimplemented two core Enumerable methods in five lines each, which is a good way to see that there is no magic in them.

block_given?

What if the caller does not pass a block? yield then raises an error. Read the message carefully, because you will see it in real programs:

Ruby yield without a block (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output is starting followed by main.rb:3:in 'Object#run': no block given (yield) (LocalJumpError). When a block is optional, ask first with block_given?:

Ruby Optional blocks with block_given?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line prints 0 1 2 first and then the return value :done, because the p call happens after the block has run three times.

More than one value

yield can pass several arguments. The block's parameters then work like a method's, with one important relaxation: a block is forgiving about the count. Missing arguments become nil, extra ones are dropped, and a single array argument is automatically spread across several parameters.

Ruby Block parameters are lenient

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

That last line works because Hash#each yields one [key, value] array, which Ruby spreads over |key, value|. Methods (and lambdas, as you will see) are strict about argument counts; blocks are not.

Passing a block along with &block

Sometimes a method needs the block as an object: to store it, to pass it to another method, or to call it later. Put &name as the last parameter and Ruby wraps the block in a Proc.

Ruby Capturing a block with &block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The block is turned into a Proc only when you ask for it with &block. A plain yield does not allocate an object, so it is somewhat faster. Use yield when you just call the block, and &block when you need to keep it or forward it.

The & also works in the other direction. Put it in front of an argument to turn an object into a block. &:upcase converts the symbol :upcase into a block that calls upcase on its argument:

Ruby & turns objects into blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby 3.1 added an anonymous form. If you only forward the block, you do not need to name it: def apply_all(list, &) = list.map(&).

The implicit parameter: it

For one-parameter blocks Ruby 3.4 introduced it, a name that is available without declaring anything. It is the modern way to write short blocks.

Ruby it and numbered parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use it when the block is short and the meaning is obvious. As soon as the block gets longer or nested, a real name such as |order| explains the code better. it works in the innermost block, which is why the nested example above is still clear.

Block-local variables and scope

A block can read and change the variables around it, because it is a closure (see Closures and Binding for the full story). Variables that are first assigned inside the block, and parameters, exist only there.

Ruby Variables inside and outside a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The third example is a classic source of bugs: a parameter with the same name as an outer variable shadows it, so the outer variable is untouched. The semicolon form |i; y| declares y as local to the block on purpose, so you can use a scratch variable without touching one of the same name outside.

Ending a block early: next, break and return

Three keywords leave a block, and they mean different things.

  • next finishes the current call of the block and goes on. With a value, next value is what yield returns.
  • break stops the method that received the block and returns from it. With a value, break value becomes the value of the whole method call.
  • return inside a block returns from the method that contains the block (the enclosing method where you wrote it), not from the block.
Ruby next, break and return side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

If each finishes without a break, it returns the receiver, which is why break is the only way to get a value out of it. When you write helper methods that search, return inside the block is perfectly fine and very readable.

There is one trap. Once a block has been turned into a Proc and called after its defining method has returned, return has nothing to return from:

Ruby return from a block whose method is gone (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get main.rb:2:in 'block in Object#make_callback': unexpected return (LocalJumpError). The remedy is a lambda, where return only leaves the lambda itself (Procs and Lambdas explains why).

Patterns that use blocks everywhere

Wrap-around: setup and cleanup

When a method needs to do something before and after the caller's code, it yields in the middle. Ruby's own File.open works that way: it opens the file, yields it, and always closes it, even when the block raises.

Ruby Resource management with ensure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The ensure clause guarantees the cleanup line runs on both paths. Callers cannot forget to close the connection, because they never do it themselves. This is the idiom behind File.open, Mutex#synchronize, Dir.chdir and Timeout.timeout.

Returning an Enumerator when no block is given

Built-in iterators return an Enumerator when called without a block, so each_with_index.map and each_slice(2).to_a work. You can give your own methods the same ability with return to_enum(:name) unless block_given?:

Ruby A method that works with and without a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Enumerators and Lazy Enumerators goes much deeper into what to_enum gives you.

Builders and configuration

Yielding self lets callers configure an object inside a block, a pattern you will use again in Building DSLs.

Ruby Yielding self for configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pitfalls and design notes

  • Do not hide control flow in yield inside loops without documenting it. Callers cannot tell how many times a block runs unless you say so.
  • A block is not an argument in the list. It is not counted in arity, and method(:name).arity ignores it. Pass it with &, never as a normal argument.
  • Prefer yield to block.call when you only call the block: it is faster and the signature stays honest.
  • Keep blocks short. If a block needs a name, a comment or its own tests, make it a method and pass &method(:name).
  • Be careful with return in blocks stored for later. Use a lambda or next.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does yield do inside a method?

    yield transfers control to the block the caller passed. Its return value is the value of the block's last expression.
  2. 2. What happens when a method calls yield but no block was given?

    You get LocalJumpError with the message no block given (yield). Check block_given? first when the block is optional.
  3. 3. Inside [3, 8, 12].each { |n| break n if n > 5 }, what does break n do?

    break ends the method that received the block and gives that call the value you pass, here 8. next only ends the current iteration.
  4. 4. A block has the parameters |a, b| and the method yields a single array [1, 2]. What are a and b?

    Blocks (unlike lambdas and methods) spread a single array argument across several parameters, and they tolerate a different number of arguments.
  5. 5. When should a method take &block instead of using a bare yield?

    &block turns the block into a Proc object you can keep and forward. For simply calling it, yield is simpler and faster.

Summary

  • A block is code passed to a method with { ... } or do ... end; the method runs it with yield.
  • yield returns the block's last value; block_given? guards optional blocks, otherwise LocalJumpError: no block given (yield) is raised.
  • Block parameters are lenient: missing values are nil, extras are dropped and one array is spread.
  • &block captures the block as a Proc; &object turns a symbol, Proc or Method into a block; it and _1 are shortcuts for short blocks.
  • Blocks see and change outer variables; a parameter with the same name shadows, and |x; y| declares block-local variables.
  • next ends one iteration, break ends the receiving method, and return leaves the method that contains the block.
  • Typical uses: iteration, wrap-around cleanup with ensure, to_enum fallbacks and configuration blocks.

Next: Procs and Lambdas