Bird
0
0

How can you create a hash with symbol keys where the values depend on a condition?

hard📝 Application Q9 of 15
Ruby - Hashes
How can you create a hash with symbol keys where the values depend on a condition?
For example, keys :a and :b with values 1 if even, else 0 for numbers 2 and 3 respectively.
A{ :a => 2.even?, :b => 3.even? }
B{ a: (2.even? ? 1 : 0), b: (3.even? ? 1 : 0) }
C{ a: 2, b: 3 }
D{ a: if 2.even? then 1 else 0 end, b: if 3.even? then 1 else 0 end }
Step-by-Step Solution
Solution:
  1. Step 1: Use ternary operator for conditional values

    { a: (2.even? ? 1 : 0), b: (3.even? ? 1 : 0) } uses condition ? true_value : false_value inline for each key's value.
  2. Step 2: Check other options

    { :a => 2.even?, :b => 3.even? } assigns boolean values, C assigns numbers directly, D uses invalid syntax inside hash literal.
  3. Final Answer:

    { a: (2.even? ? 1 : 0), b: (3.even? ? 1 : 0) } -> Option B
  4. Quick Check:

    Use ternary inside hash values for conditions [OK]
Quick Trick: Use ternary ?: inside hash values for conditions [OK]
Common Mistakes:
  • Using if/else statements directly inside hash literal
  • Assigning booleans instead of desired values
  • Not using parentheses for expressions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes