Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
arr1 = [4, 5, 6]
arr2 = ['x', 'y']
result = arr1.zip(arr2)
puts result.inspect
A[[4, "x"], [5, "y"], [6, nil]]
B[[4, "x"], [5, "y"]]
C[[4, 5, 6], ["x", "y"]]
DError due to different array sizes
Step-by-Step Solution
Solution:
  1. Step 1: Understand zip with unequal lengths

    If arrays differ in length, zip fills missing elements with nil.
  2. Step 2: Apply to given arrays

    Third element of arr1 has no pair, so paired with nil.
  3. Final Answer:

    [[4, "x"], [5, "y"], [6, nil]] -> Option A
  4. Quick Check:

    Check for nil in last pair [OK]
Quick Trick: Missing pairs become nil in zipped arrays [OK]
Common Mistakes:
  • Expecting shorter array to truncate result
  • Assuming error on length mismatch
  • Ignoring nil padding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes