Challenge - 5 Problems
Block Given 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 block_given??
Consider the following Ruby method that checks if a block is given and yields to it if so. What will be printed when calling
greet with and without a block?Ruby
def greet if block_given? yield else puts "No block given" end end greet greet { puts "Hello from block!" }
Attempts:
2 left
💡 Hint
Remember that
block_given? returns true only if a block is passed to the method.✗ Incorrect
The first call to
greet has no block, so it prints "No block given". The second call has a block, so it yields and prints "Hello from block!".🧠 Conceptual
intermediate1:30remaining
What does
block_given? return inside a method?In Ruby, what does the method
block_given? return when called inside a method?Attempts:
2 left
💡 Hint
Think about whether the method itself received a block or not.
✗ Incorrect
block_given? returns true only if the current method was called with a block.🔧 Debug
advanced2:00remaining
Why does this code raise an error when using yield without block_given??
Look at this Ruby method:
def run yield end runWhat error will this code raise and why?
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 expects a block to execute.
❓ Predict Output
advanced2:00remaining
What is the output of this method using block_given? and yield?
What will this Ruby code print?
def check
if block_given?
yield(5)
else
puts "No block"
end
end
check { |x| puts x * 2 }
checkAttempts:
2 left
💡 Hint
The block receives the number 5 and multiplies it by 2.
✗ Incorrect
The first call passes a block that prints 5 * 2 = 10. The second call has no block, so it prints "No block".
🧠 Conceptual
expert2:30remaining
How does
block_given? behave with nested method calls?Given these Ruby methods:
def outer
inner
end
def inner
block_given?
end
result = outer { puts "Hi" }
What is the value of result after this code runs?Attempts:
2 left
💡 Hint
Does the block passed to outer get passed automatically to inner?
✗ Incorrect
The block is given to outer, but inner does not receive it unless explicitly passed. So
block_given? inside inner returns false.