Bird
0
0

Given the method below, what will be the output?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
Given the method below, what will be the output?
def repeat(n)
  if block_given?
    n.times { |i| yield(i) }
  else
    puts "No block given"
  end
end

repeat(3) { |num| puts num * 2 }
A0 1 2
B1 2 3
C0 2 4
DNo block given
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the method behavior

    The method repeat checks if a block is given. Since a block is passed, it runs n.times and yields the index i to the block.
  2. Step 2: Evaluate the block execution

    The block multiplies each yielded number by 2 and prints it. For n=3, i goes 0,1,2, so outputs are 0, 2, 4.
  3. Final Answer:

    0 2 4 -> Option C
  4. Quick Check:

    Yield with times and block multiplies index = D [OK]
Quick Trick: Yield passes each index to block in times loop [OK]
Common Mistakes:
  • Confusing index values starting at 1
  • Ignoring block_given? check
  • Expecting output without block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes