Bird
0
0

Given hash = {a: 1, b: nil, c: 3, d: nil}, which code removes all keys with nil values?

hard📝 Application Q9 of 15
Ruby - Variables and Data Types
Given hash = {a: 1, b: nil, c: 3, d: nil}, which code removes all keys with nil values?
Ahash.reject! { |k, v| v != nil }
Bhash.delete_if { |k, v| v.nil? }
Chash.select { |k, v| v.nil? }
Dhash.keep_if { |k, v| v.nil? }
Step-by-Step Solution
Solution:
  1. Step 1: Understand delete_if method

    delete_if removes key-value pairs matching the condition.
  2. Step 2: Remove pairs where value is nil

    Use v.nil? to identify nil values and delete those pairs.
  3. Final Answer:

    hash.delete_if { |k, v| v.nil? } -> Option B
  4. Quick Check:

    delete_if removes nil values = C [OK]
Quick Trick: Use delete_if with .nil? to clean hashes [OK]
Common Mistakes:
  • Using select to keep nils
  • Using reject! with wrong condition
  • Using keep_if to keep nils

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes