This program shows a method that yields two spices to a block, which then prints a message using them.
Ruby
def cooking
puts"Start cooking"yield("salt", "pepper")
puts"Done cooking"end
cooking do |spice1, spice2|
puts"Add #{spice1} and #{spice2} to the dish"end
OutputSuccess
Important Notes
Use block_given? to check if a block was passed before calling yield.
You can pass values to the block by giving arguments to yield.
Blocks make your methods more flexible and let users add custom behavior.
Summary
Yield runs the block given to a method.
You can pass data to the block using yield with arguments.
Always check for a block with block_given? to avoid errors.
Practice
(1/5)
1. What does the yield keyword do in a Ruby method?
easy
A. It runs the block of code passed to the method.
B. It returns the method's value immediately.
C. It defines a new method inside the current method.
D. It pauses the method execution permanently.
Solution
Step 1: Understand the role of yield
The yield keyword is used inside a method to call the block that was passed to that method.
Step 2: Differentiate from other keywords
Unlike return or method definitions, yield specifically executes the block given to the method.
Final Answer:
It runs the block of code passed to the method. -> Option A
Quick Check:
Yield executes block = A [OK]
Hint: Yield always runs the block given to the method [OK]
Common Mistakes:
Thinking yield returns method value
Confusing yield with return
Assuming yield defines a method
2. Which of the following is the correct syntax to use yield with an argument inside a method?
easy
A. def example; yield(5); end
B. def example; yield5; end
C. def example; yield = 5; end
D. def example; yield: 5; end
Solution
Step 1: Recall yield syntax with arguments
To pass arguments to the block, yield must be called with parentheses around the arguments, like yield(5).
Step 2: Check other options for syntax errors
Options B, C, and D are incorrect because they either miss parentheses or use invalid syntax.
Final Answer:
def example; yield(5); end -> Option A
Quick Check:
Yield with args uses parentheses = A [OK]
Hint: Use parentheses to pass arguments with yield [OK]
Common Mistakes:
Omitting parentheses when passing arguments
Using assignment (=) with yield
Using colon (:) instead of parentheses
3. What will be the output of the following Ruby code?