Bird
0
0

Given this code, what will be the output?

hard📝 Application Q8 of 15
Ruby - Blocks, Procs, and Lambdas
Given this code, what will be the output?
def repeat(n)
  n.times { yield }
end
count = 0
repeat(3) do
  count += 1
  puts count
end
A1 2 3 (each on a new line)
B3 3 3 (each on a new line)
C0 1 2 (each on a new line)
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand the repeat method with yield

    The method calls the block n times using n.times { yield }.
  2. Step 2: Trace the block execution

    Each time the block runs, it increments count by 1 and prints it. So it prints 1, then 2, then 3 on separate lines.
  3. Final Answer:

    1 2 3 (each on a new line) -> Option A
  4. Quick Check:

    yield with times increments count = A [OK]
Quick Trick: yield calls the block passed to the method [OK]
Common Mistakes:
  • Thinking count resets each time
  • Expecting repeated same number
  • Missing yield usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes