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

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.
Syntax
ruby
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

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
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
  1. Expecting select on a hash to return an array, when it returns a hash.
  2. Using a block with one parameter like { |pair| pair >= 70 }, comparing an array instead of the score.
  3. Expecting select to change the hash, when it returns a new one unless you use select!.
🔒

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.