Challenge - 5 Problems
Yield Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using yield?
Consider the following Ruby method that uses
yield. What will be printed when this code runs?Ruby
def greet puts "Hello" yield if block_given? puts "Goodbye" end greet { puts "How are you?" }
Attempts:
2 left
💡 Hint
Remember that
yield runs the block passed to the method exactly where it appears.✗ Incorrect
The method prints "Hello", then yields to the block which prints "How are you?", then prints "Goodbye".
🧠 Conceptual
intermediate1:30remaining
What does
block_given? check in Ruby?In Ruby, inside a method, what does the method
block_given? return?Attempts:
2 left
💡 Hint
Think about how Ruby methods detect if a block was passed.
✗ Incorrect
block_given? returns true only if the caller passed a block to the method.🔧 Debug
advanced2:00remaining
Why does this Ruby code raise an error?
Look at this Ruby method and its call. Why does it raise a LocalJumpError?
Ruby
def run_block yield yield end run_block
Attempts:
2 left
💡 Hint
What happens if you call yield but no block is given?
✗ Incorrect
Calling yield without a block causes a LocalJumpError because Ruby doesn't know what to execute.
📝 Syntax
advanced1:30remaining
Which option correctly defines a method that yields to a block with a parameter?
You want to define a Ruby method that yields a value to a block. Which code is correct?
Attempts:
2 left
💡 Hint
Check for correct parentheses and syntax around yield.
✗ Incorrect
Option D correctly calls yield with an argument 10. Others have syntax errors like missing or extra parentheses.
🚀 Application
expert2:30remaining
What is the output of this Ruby code using yield with multiple yields and parameters?
Analyze this Ruby code and select the exact output it produces.
Ruby
def multi_yield yield(1) yield(2) yield(3) end result = [] multi_yield { |x| result << x * 2 } puts result.join(",")
Attempts:
2 left
💡 Hint
The block doubles each yielded value and appends it to the array.
✗ Incorrect
The method yields 1, 2, and 3. The block multiplies each by 2 and appends to result. Output is '2,4,6'.