midRuby
What are Ruby blocks, and how does the 'yield' keyword work?
Updated May 17, 2026
Short answer
yield transfers execution control from the host method body directly into the attached code block, optionally passing specific parameters.
Deep explanation
A block is an anonymous chunk of code passed to a method during invocation. Inside that method, using the yield keyword pauses method execution and hands control over to the block. Once the block executes, it returns its final expression value back to the exact location of the yield call inside the method.
Real-world example
Implementing profiling wrappers or database transaction rollbacks where code blocks must be safely isolated between open and close handlers.
Common mistakes
- Calling `yield` when no block was provided by the user, resulting in a fatal `LocalJumpError`. Always protect optional yields using `block_given?` checkpoints.
Follow-up questions
- How do you pass arguments to a yield block?
- What is the alternative way to capture a block instead of using yield?