select and reject on Hashes
select and reject on a hash filter its pairs by a rule, like picking only the contacts who live nearby. select keeps the matches and reject removes them.
In this page:
Syntax
filtered = hash.select { |key, value| condition }
filtered = hash.reject { |key, value| condition }
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
selecton a hash to return an array, when it returns a hash. - Using a block with one parameter like
{ |pair| pair >= 70 }, comparing an array instead of the score. - Expecting
selectto change the hash, when it returns a new one unless you useselect!.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: