Hash#filter

hash.filter { |key, value| block } -> hash
Returns: Hash · Updated March 13, 2026 · Hash Methods
hash filtering enumerable

filter returns a new hash containing only the key-value pairs where the block returns a truthy value.

Syntax

hash.filter { |key, value| condition }

Parameters

ParameterTypeDefaultDescription
blockProcRequiredA 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.filter { |name, score| score > 85 }
# => {:alice=>95, :diana=>90}

Filtering by key

config = { host: "localhost", port: 8080, debug: true, ssl: false }

# Keep only string values
string_vals = config.filter { |_key, value| value.is_a?(String) }
# => {:host=>"localhost"}

Practical example

user_input = { name: "Alice", age: "25", email: "alice@example.com", phone: nil }

# Keep only non-empty values
cleaned = user_input.reject { |_key, value| value.nil? || value.to_s.strip.empty? }
# => {:name=>"Alice", :age=>"25", :email=>"alice@example.com"}

Common Patterns

Chaining with transform

data = { a: 1, b: 2, c: 3, d: 4, e: 5 }

filtered_then_doubled = data.filter { |k, v| v > 2 }.transform_values { |v| v * 2 }
# => {:c=>6, :d=>8, :e=>10}

See Also