select and reject on Hashes
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: