Bird
0
0

Given this code:

hard📝 Application Q15 of 15
Ruby - Operators and Expressions
Given this code:
settings = { theme: nil, font_size: 12 }
settings[:theme] ||= 'dark'
settings[:font_size] ||= 14
puts settings[:theme]
puts settings[:font_size]

What is the output and why?
Anil\n14 because theme is nil and font_size is replaced
Bdark\n12 because theme was nil and font_size was truthy
Cdark\n14 because both keys were nil or false
Dnil\n12 because ||= does not work on hashes
Step-by-Step Solution
Solution:
  1. Step 1: Check initial values in settings hash

    settings[:theme] is nil, settings[:font_size] is 12 (truthy).
  2. Step 2: Apply conditional assignment

    settings[:theme] ||= 'dark' sets theme to 'dark' because it was nil.
    settings[:font_size] ||= 14 does not change font_size because 12 is truthy.
  3. Final Answer:

    dark 12 -> Option B
  4. Quick Check:

    Nil replaced, truthy kept = dark and 12 [OK]
Quick Trick: ||= sets defaults only if current value is nil or false [OK]
Common Mistakes:
  • Assuming 12 is replaced by 14
  • Thinking ||= doesn't work on hash values
  • Confusing nil with false values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes