Bird
0
0

You want to set a default value for a hash key only if it is missing or nil. Which code correctly uses ||= for this?

hard📝 Application Q8 of 15
Ruby - Operators and Expressions
You want to set a default value for a hash key only if it is missing or nil. Which code correctly uses ||= for this?
settings = { theme: nil }
settings[:theme] ||= "dark"
puts settings[:theme]
ARaises error because hash keys can't use ||=
BOutputs "dark" because theme was nil
COutputs nil because ||= does not work on hash keys
DOutputs nil because theme key exists
Step-by-Step Solution
Solution:
  1. Step 1: Check initial value of settings[:theme]

    It is nil, so falsy.
  2. Step 2: Apply ||= operator on hash key

    Since nil, settings[:theme] ||= "dark" assigns "dark".
  3. Final Answer:

    Outputs "dark" because theme was nil -> Option B
  4. Quick Check:

    ||= works on hash values, assigns if nil [OK]
Quick Trick: ||= works on hash values to set defaults [OK]
Common Mistakes:
  • Thinking ||= can't be used on hash keys
  • Assuming existing key prevents assignment
  • Expecting error on ||= with hashes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes