Bird
0
0

What does the Ruby operator ||= do when used like x ||= 10?

easy📝 Conceptual Q11 of 15
Ruby - Operators and Expressions
What does the Ruby operator ||= do when used like x ||= 10?
AAlways assigns 10 to x, replacing any value
BAssigns 10 to x only if x is true
CAssigns 10 to x only if x is nil or false
DThrows an error if x is already assigned
Step-by-Step Solution
Solution:
  1. Step 1: Understand the ||= operator

    The operator ||= assigns the right side value only if the left side variable is nil or false.
  2. Step 2: Apply to example x ||= 10

    If x is nil or false, it becomes 10; otherwise, it keeps its current value.
  3. Final Answer:

    Assigns 10 to x only if x is nil or false -> Option C
  4. Quick Check:

    Conditional assignment = Assign if nil/false [OK]
Quick Trick: ||= sets value only if variable is nil or false [OK]
Common Mistakes:
MISTAKES
  • Thinking ||= always assigns the value
  • Confusing ||= with simple assignment =
  • Assuming ||= assigns when variable is true

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes