Hash#select
hash.select { |key, value| block } -> hash Returns:
Hash · Updated March 13, 2026 · Hash Methods hash filtering enumerable
select is an alias for filter. It returns a new hash containing only the key-value pairs where the block returns a truthy value.
Syntax
hash.select { |key, value| condition }
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | Proc | Required | A block receiving key and value. Return truthy to keep the pair. |
Examples
Basic usage
scores = { alice: 95, bob: 82, charlie: 78, diana: 90 }
# Keep only scores above 85
passing = scores.select { |name, score| score > 85 }
# => {:alice=>95, :diana=>90}
Filtering by value type
config = { host: "localhost", port: 8080, debug: true, ssl: false }
# Keep only string values
string_vals = config.select { |_key, value| value.is_a?(String) }
# => {:host=>"localhost"}
Practical example
inventory = { apples: 0, bananas: 5, oranges: 3, grapes: 0 }
# Keep only items in stock
in_stock = inventory.select { |item, count| count > 0 }
# => {:bananas=>5, :oranges=>3}
Common Patterns
Chaining with transform
prices = { apple: 1.50, banana: 0.75, orange: 1.00, grape: 2.50 }
# Filter expensive items, then apply discount
discounted = prices.select { |_k, v| v > 1.0 }.transform_values { |v| v * 0.9 }
# => {:apple=>1.35, :grape=>2.25}
In-place filtering (Ruby 2.5+)
data = { x: 1, y: 2, z: 3 }
data.select! { |_k, v| v > 1 }
# => {:y=>2, :z=>3}