Bird
0
0

You have two hashes:

hard📝 Application Q15 of 15
Ruby - Hashes

You have two hashes:

h1 = {a: 1, b: 2, c: 3}
h2 = {b: 20, d: 4}

You want to update h1 with h2 but only keep keys from h2 that have values greater than 10. Which code correctly does this?

Ah1.update(h2.select { |k, v| v > 10 })
Bh1.update(h2.reject { |k, v| v > 10 })
Ch1.merge(h2.select { |k, v| v > 10 })
Dh1.replace(h2.select { |k, v| v > 10 })
Step-by-Step Solution
Solution:
  1. Step 1: Filter h2 keys with values > 10

    Use select { |k, v| v > 10 } to keep only keys with values greater than 10.
  2. Step 2: Update h1 with filtered h2

    Use update to modify h1 in place with the filtered hash.
  3. Step 3: Check other options

    merge! also updates but update is clearer; merge returns new hash and does not modify h1.
  4. Final Answer:

    h1.update(h2.select { |k, v| v > 10 }) -> Option A
  5. Quick Check:

    Filter then update original hash [OK]
Quick Trick: Filter with select, then update original hash [OK]
Common Mistakes:
MISTAKES
  • Using merge instead of update (does not modify original)
  • Not filtering keys before update
  • Using reject incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes