Challenge - 5 Problems
Ruby Blocks Mastery
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 a block?
Consider the following Ruby code that uses a block with the method
times. What will it print?Ruby
3.times do |i| puts i * 2 end
Attempts:
2 left
💡 Hint
Remember that the block variable
i starts at 0 and goes up to one less than the number.✗ Incorrect
The times method runs the block 3 times with i values 0, 1, and 2. Multiplying each by 2 gives 0, 2, and 4.
🧠 Conceptual
intermediate1:30remaining
Why are blocks important in Ruby?
Which of the following best explains why blocks are fundamental to Ruby?
Attempts:
2 left
💡 Hint
Think about how blocks let you pass code to methods like
each or map.✗ Incorrect
Blocks let you pass a piece of code to a method, which can run it multiple times or at specific moments. This makes Ruby very flexible and expressive.
🔧 Debug
advanced2:00remaining
What error does this Ruby code raise?
Look at this Ruby code using a block. What error will it raise when run?
Ruby
def greet yield yield('friend') end greet do |name| puts "Hello, #{name}!" end
Attempts:
2 left
💡 Hint
Check how many arguments the block expects and how many are passed.
✗ Incorrect
The block expects one argument (name), but the first yield call passes none, causing an ArgumentError.
📝 Syntax
advanced1:30remaining
Which option correctly defines a method that takes a block and calls it twice?
Choose the Ruby code that defines a method
twice which calls the given block two times.Attempts:
2 left
💡 Hint
Blocks can be called with
yield or by passing an explicit block parameter.✗ Incorrect
All three ways correctly call the block twice. Option C and C use yield, B uses an explicit block parameter.
🚀 Application
expert2:30remaining
What is the output of this Ruby code using blocks and enumerators?
Analyze this Ruby code and select the exact output it produces.
Ruby
result = (1..5).map do |n| if n.even? n * 2 else n end end puts result.inspect
Attempts:
2 left
💡 Hint
Remember that
n.even? checks if a number is even, and map transforms each element.✗ Incorrect
For even numbers (2 and 4), the block returns n * 2 (4 and 8). For odd numbers, it returns n unchanged. So the array becomes [1, 4, 3, 8, 5].