Bird
0
0

Given an array words = ['cat', 'dog', 'cat', 'bird'], which Ruby code snippet correctly uses a hash with a default value to count the frequency of each word?

hard📝 Application Q8 of 15
Ruby - Hashes
Given an array words = ['cat', 'dog', 'cat', 'bird'], which Ruby code snippet correctly uses a hash with a default value to count the frequency of each word?
Acounts = Hash.new; words.each { |w| counts[w] = counts[w] + 1 }
Bcounts = Hash.new([]); words.each { |w| counts[w] += 1 }
Ccounts = Hash.new(0); words.each { |w| counts[w] += 1 }
Dcounts = {}; words.each { |w| counts[w] = 1 }
Step-by-Step Solution
Solution:
  1. Step 1: Initialize hash with default 0

    Using Hash.new(0) ensures missing keys return 0, allowing increment.
  2. Step 2: Iterate and increment counts

    For each word, increment the count by 1.
  3. Final Answer:

    counts = Hash.new(0); words.each { |w| counts[w] += 1 } -> Option C
  4. Quick Check:

    Check if missing keys start at 0 and increment correctly [OK]
Quick Trick: Use Hash.new(0) for counting frequencies [OK]
Common Mistakes:
  • Using Hash.new([]) which returns the same array for all keys
  • Not initializing default value, causing nil errors on increment
  • Assigning 1 to each key without incrementing counts

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes