Bird
0
0

Given a hash h = {a: 1, b: nil, c: 3, d: nil}Which Ruby code removes all key-value pairs where the value is nil using compact?

hard📝 Application Q9 of 15
Ruby - Arrays

Given a hash h = {a: 1, b: nil, c: 3, d: nil}

Which Ruby code removes all key-value pairs where the value is nil using compact?

Ah.compact
Bh.delete_if { |k, v| v.nil? }
Ch.compact!
DBoth B and C
Step-by-Step Solution
Solution:
  1. Step 1: Understand compact on Hash

    Ruby 2.4+ supports compact and compact! on Hash to remove pairs with nil values.
  2. Step 2: Compare with delete_if

    delete_if { |k, v| v.nil? } also removes pairs with nil values by filtering.
  3. Step 3: Confirm both methods work

    Both compact! and delete_if modify the hash in place to remove nil values, so both are correct.
  4. Final Answer:

    Both B and C -> Option D
  5. Quick Check:

    compact! and delete_if remove nil pairs = A [OK]
Quick Trick: Use compact! or delete_if to remove nil pairs from hash [OK]
Common Mistakes:
  • Thinking compact does not work on Hash
  • Confusing compact and compact! on Hash
  • Expecting compact to return new hash without assignment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes