← Back to Ruby Course | Chapter 5: Hashes | Lesson 5 of 7

select and reject on Hashes

select and reject on Hashes

hash.select { |k, v| ... } returns a new hash containing only the pairs for which the block is true, and reject returns the pairs for which it's false -- the same filtering idea as on arrays, applied to key-value pairs. Both return a Hash, not an array, when called on a hash. This is the idiomatic way to filter a hash based on its keys or values.

Note: select/reject on a Hash return a Hash back, unlike map which returns an Array -- a useful distinction to remember.

Example: select and reject on Hashes

markup
scores = { alice: 95, bob: 60, cara: 80 }

passing = scores.select { |name, score| score >= 70 }
failing = scores.reject { |name, score| score >= 70 }

puts passing.inspect
puts failing.inspect
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.