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 You're handing .each a set of instructions saying "do puts n for each element."
1 2 3 { } 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 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?" } Hello How are you? ← the block gets inserted where yield is Goodbye 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 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 Usage:
with_debug do # Logging is debug only inside here user.save! end # Once you leave this, the log level is automatically restored 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."
-
ensureguarantees 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 "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.
