0
0
RubyHow-ToBeginner · 3 min read

How to Select from Hash in Ruby: Syntax and Examples

In Ruby, you can select key-value pairs from a hash using the select method with a block that returns true for desired pairs. The method returns a new hash containing only the pairs that meet the condition inside the block.
📐

Syntax

The select method is called on a hash and takes a block with two parameters: key and value. Inside the block, you write a condition that returns true for pairs you want to keep.

  • hash.select { |key, value| condition }
  • Returns a new hash with pairs where condition is true.
ruby
selected_hash = hash.select { |key, value| value > 10 }
💻

Example

This example shows how to select all key-value pairs from a hash where the value is greater than 10.

ruby
scores = { alice: 15, bob: 8, carol: 22, dave: 5 }
high_scores = scores.select { |name, score| score > 10 }
puts high_scores
Output
{:alice=>15, :carol=>22}
⚠️

Common Pitfalls

A common mistake is to use select without a block or with a block that does not return a boolean value. Also, select returns a new hash and does not modify the original hash unless you use select!.

Wrong usage example:

hash.select

Right usage example:

hash.select { |k, v| v.even? }
ruby
numbers = { a: 1, b: 2, c: 3 }
# Wrong: no block given
# numbers.select

# Right: block returns boolean
even_numbers = numbers.select { |k, v| v.even? }
puts even_numbers
Output
{:b=>2}
📊

Quick Reference

MethodDescription
select { |k, v| condition }Returns a new hash with pairs matching the condition
select!Modifies the original hash by keeping pairs matching the condition
reject { |k, v| condition }Returns a new hash excluding pairs matching the condition
reject!Modifies the original hash by removing pairs matching the condition

Key Takeaways

Use the select method with a block to filter hash pairs by condition.
select returns a new hash and does not change the original hash.
Always provide a block that returns true or false for each pair.
Use select! if you want to modify the original hash in place.
reject and reject! are useful opposites to select and select!.