Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Blocks, Procs, and Lambdas
What will this Ruby code print?
def count_down(n)
  while n > 0
    yield n
    n -= 1
  end
end
count_down(3) { |i| puts i * 2 }
A3 2 1
B6 4 2
C2 4 6
DError: block missing
Step-by-Step Solution
Solution:
  1. Step 1: Trace the loop and block calls

    The method counts down from 3 to 1, yielding each number to the block.
  2. Step 2: Calculate block output for each yield

    The block multiplies each number by 2, printing 6, then 4, then 2.
  3. Final Answer:

    6 4 2 -> Option B
  4. Quick Check:

    Block multiplies each number by 2 [OK]
Quick Trick: Block runs for each yielded value [OK]
Common Mistakes:
  • Confusing order of output
  • Expecting original numbers
  • Forgetting block multiplies by 2

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes