`

# 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:
  1. 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.
  2. Flexible Methods: It allows methods to be more flexible and reusable by enabling custom behavior to be defined outside the method.
  3. Passing Arguments: You can pass arguments to the block using yield, which the block can then use.
  4. 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