DEV Community

Kaziu
Kaziu

Posted on

Ruby Blocks and yield Explained with the Simplest Examples

If you write Ruby, you'll always run into "blocks" and "yield."
They look tricky, but really it's just "passing some code" and "running the code you were passed."

What's a block?

It's a "chunk of code (a little snippet)" you pass to a method.
You wrap it in { } or do...end.

[1, 2, 3].each { |n| puts n }
#              └──────────┘ this is the block
Enter fullscreen mode Exit fullscreen mode

You're handing .each a set of instructions saying "do puts n for each element."

1
2
3
Enter fullscreen mode Exit fullscreen mode

{ } and do...end are the same thing. You just use do...end when it gets long.

[1, 2, 3].each do |n|
  puts n
end
Enter fullscreen mode Exit fullscreen mode

What's yield?

It's an instruction that runs the passed-in block at "the spot where you wrote yield" inside the method.

def greet
  puts "Hello"
  yield              # ← run the passed-in block here
  puts "Goodbye"
end

greet { puts "How are you?" }
Enter fullscreen mode Exit fullscreen mode
Hello
How are you?    ← the block gets inserted where yield is
Goodbye
Enter fullscreen mode Exit fullscreen mode

You can put yield anywhere, call it as many times as you like, and even pass values to it.

def count_up
  yield 1
  yield 2
end

count_up { |n| puts "Item #{n}" }
# Item 1
# Item 2
Enter fullscreen mode Exit fullscreen mode

How the two relate

  • Block = the "to-do note" you pass (written by the caller)
  • yield = the instruction that runs that note (written by the method)

The method decides where it gets inserted; the caller decides what gets inserted.


In practice: "wrapping" code with yield

The really handy use of yield is the pattern of wrapping the passed-in code with shared setup and cleanup.

def with_debug
  old = Rails.logger.level
  Rails.logger.level = :debug   # Setup: switch logging to debug
  yield                         # Run the caller's code
ensure # Always runs at the end, whether an error happens or not (= finally)
  Rails.logger.level = old      # Cleanup: always restore it
end
Enter fullscreen mode Exit fullscreen mode

Usage:

with_debug do
  # Logging is debug only inside here
  user.save!
end
# Once you leave this, the log level is automatically restored
Enter fullscreen mode Exit fullscreen mode

Why it's handy

  • You can keep the shared part (switching and restoring the log level) in one place. The caller only has to write "what they want to do."
  • ensure guarantees the cleanup. Even if an error happens inside the block, the log level always gets restored.

Without yield, you'd be stuck copy-pasting "switch → do the work → restore" every single place you use it. With yield, you can split things cleanly: the frame (setup/cleanup) lives in the method, the contents come from the caller.

Another example: measuring execution time

You can write "measure execution time" with the same pattern.

def measure(label)
  start = Time.now
  yield
ensure
  puts "#{label}: #{Time.now - start} sec"
end

measure("Heavy task") do
  heavy_task
end
# => Heavy task: 1.23 sec
Enter fullscreen mode Exit fullscreen mode

"Wrap a block with shared setup and cleanup" — this is a super common design pattern in Ruby.
Things like File.open { |f| ... } (open it and always close it) belong to the same family.

Top comments (0)