Bird
0
0

Given a hash scores = { alice: 10, bob: 15, carol: 7 }, how can you use an iterator to create a new hash with only scores greater than 8?

hard📝 Application Q15 of 15
Ruby - Loops and Iteration
Given a hash scores = { alice: 10, bob: 15, carol: 7 }, how can you use an iterator to create a new hash with only scores greater than 8?
Ascores.map { |name, score| score > 8 }
Bscores.each { |name, score| score > 8 }
Cscores.select { |name, score| score > 8 }
Dscores.filter { |name, score| score < 8 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want a new hash with only entries where the score is greater than 8.
  2. Step 2: Choose the right iterator method

    select filters a hash by condition and returns a new hash with matching pairs.
  3. Step 3: Check each option

    scores.select { |name, score| score > 8 } uses select with correct condition. scores.each { |name, score| score > 8 } uses each which returns original hash, not filtered. scores.map { |name, score| score > 8 } uses map which returns an array of booleans. scores.filter { |name, score| score < 8 } filters for scores less than 8, opposite of requirement.
  4. Final Answer:

    scores.select { |name, score| score > 8 } -> Option C
  5. Quick Check:

    Use select to filter hash = A [OK]
Quick Trick: Use select with condition to filter hashes [OK]
Common Mistakes:
  • Using each instead of select for filtering
  • Using map which changes structure
  • Filtering with wrong condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes