Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Arrays
What is the output of the following Ruby code?
arr = Array.new(4) { |i| i * 2 }
puts arr.inspect
A[nil, nil, nil, nil]
B[2, 4, 6, 8]
C[0, 2, 4, 6]
D[0, 0, 0, 0]
Step-by-Step Solution
Solution:
  1. Step 1: Understand Array.new with block

    When Array.new is called with a block, it runs the block for each index, passing the index as i.
  2. Step 2: Calculate each element

    For indices 0 to 3, the block returns i * 2: 0*2=0, 1*2=2, 2*2=4, 3*2=6.
  3. Final Answer:

    [0, 2, 4, 6] -> Option C
  4. Quick Check:

    Array with block fills elements by index * 2 [OK]
Quick Trick: Array.new with block uses index to set each element [OK]
Common Mistakes:
  • Assuming default value 0 for all elements
  • Confusing block argument meaning
  • Expecting nil values without block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes