Thuta Learning
AdvancedProgrammingbeginner

Blocks & Yield

Relax. We'll talk through this in plain words — no textbook voice.

Block is a chunk of code that tags along right after a method call. You'll run into blocks constantly with Ruby iterators, file handling, and callbacks. If you want to run a block from inside a method, that's what yield is for.

ruby
def with_loading
  puts "Loading..."
  yield
  puts "Done!"
end

with_loading do
  puts "Fetching user data"
end

with_loading method, you're also handing it a block. Wherever yield shows up inside the method, that's where the block's code runs.

You should see
Loading... Fetching user data Done!

Info

Calling yield without a block can throw an error. If you need to, you can check first with block_given?.

Easy traps

  • Don't forget the |value| syntax once block parameters come into play. For example: items.each { |item| puts item }.