yield
When working with blocks in Ruby, the yield
keyword allows us to invoke a block of code passed to a method. It essentially transfers control from the method to the block, executing the block's code within the method's context. The yield
keyword is used within the method to indicate the point where the block should be executed.
Let's consider an example to understand how yield
works:
def greet
puts "Hello!"
yield if block_given?
puts "Goodbye!"
end
greet do
puts "Welcome to the Ruby world!"
end
In this example, we define a method called greet
that prints "Hello!" before yielding control to the block. The yield
keyword is used to invoke the block passed to the method. After the block execution, the method continues to execute and prints "Goodbye!".
When we call greet
with a block, the output will be:
Hello!
Welcome to the Ruby world!
Goodbye!
Here, the block puts "Welcome to the Ruby world!"
is passed to the greet
method. The yield
keyword executes the block, printing "Welcome to the Ruby world!" within the greet
method's context.
The yield
keyword can also pass arguments to the block if necessary. Let's modify the previous example:
def greet
puts "Hello!"
yield("John") if block_given?
puts "Goodbye!"
end
greet do |name|
puts "Welcome, #{name}!"
end
Output:
Hello!
Welcome, John!
Goodbye!
In this example, the greet
method now yields control to the block while passing the argument "John" using yield("John")
. The block receives the argument as a parameter and prints "Welcome, John!" within the greet
method's context.
Understanding yield
is essential for working with blocks in Ruby. It provides a way to encapsulate and pass around behavior as code, enabling more flexible and reusable code.
During the interview, it's important to explain the concept clearly and provide examples that highlight how yield
allows method-level code to interact with block-level code.
Last updated