# What is the use of yield in ruby?
191
In Ruby, the yield keyword is used within a method to transfer control to a block provided during the method call. Here’s how it works:
- Block Execution: When a method containing yield is called with a block, the code within the block is executed at the point where yield appears.
- Flexible Methods: It allows methods to be more flexible and reusable by enabling custom behavior to be defined outside the method.
- Passing Arguments: You can pass arguments to the block using yield, which the block can then use.
- Cleaner Code: It helps in writing cleaner and more readable code by separating the method logic from the block logic.
Here’s a simple example:
def greet yield "Hello" end greet { |message| puts message } # Outputs: Hello