Functions

Ruby Yield

Using Yield

Ruby yield passes control to blocks in methods.

What is Ruby Yield?

In Ruby, the yield keyword is used within a method to transfer control to an associated block. This allows for a flexible method design where a block of code can be passed as a parameter to a method, giving you the ability to define custom behaviors on the fly.

How Does Yield Work?

When a method containing the yield keyword is called with a block, the execution of the method pauses at the yield and temporarily jumps to the block. Once the block is executed, control returns to the method, continuing right after the yield. If no block is provided, calling yield will result in a LocalJumpError.

Basic Example of Yield

In this example, the greet method calls yield between two puts statements. The block { puts "Nice to meet you!" } is executed when yield is called. The output will be:

Yield with Parameters

Yield can also pass parameters to the block. This is done by providing arguments to the yield keyword, which are then captured by the block's parameters.

In this example, the calculate method uses yield to pass the numbers 5 and 3 to the block, which then adds them together and prints the result 8.

Checking for a Block with block_given?

To avoid errors when calling yield without a block, use the block_given? method. This checks if a block is provided before attempting to call yield.

Here, the safe_greeting method checks for a block with block_given?. If a block is not provided, it prints "No block given." instead of raising an error. The outputs will be:

Conclusion

The yield keyword in Ruby is a powerful feature that allows methods to call blocks, providing a high level of flexibility and reusability. By passing control to blocks, you can create methods with customizable behaviors, making your code more modular and easier to maintain.

Previous
Lambdas