Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Loops and Iteration
What will be the output of this Ruby code?
arr = [1, 2, 3]
arr.each { |n| puts n * 2 }
A2 4 6
B1 2 3
CError: undefined method
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand the iterator block

    The each method passes each element to the block variable n.
  2. Step 2: Calculate output for each element

    Each element is multiplied by 2 and printed: 1*2=2, 2*2=4, 3*2=6.
  3. Final Answer:

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

    Output of arr.each with n*2 = A [OK]
Quick Trick: each passes elements to block; output is block result printed [OK]
Common Mistakes:
  • Expecting original values instead of multiplied
  • Confusing each with map (which returns new array)
  • Thinking code causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes