Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Operators and Expressions
What will be the output of this Ruby code?
a = nil
b = 20
a ||= 10
b ||= 30
puts a
puts b
A10\n30
Bnil\n30
Cnil\n20
D10\n20
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate a ||= 10 when a is nil

    Since a is nil, a ||= 10 assigns 10 to a.
  2. Step 2: Evaluate b ||= 30 when b is 20

    Since b is already 20 (truthy), b ||= 30 does not change b.
  3. Final Answer:

    10 20 -> Option D
  4. Quick Check:

    nil replaced, truthy kept = 10 and 20 [OK]
Quick Trick: ||= changes only nil or false variables [OK]
Common Mistakes:
  • Assuming b changes to 30
  • Thinking nil stays nil after ||= 10
  • Mixing up output order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes