Filtering hashes

suggest change

select returns a new hash with key-value pairs for which the block evaluates to true.

{ :a => 1, :b => 2, :c => 3 }.select { |k, v| k != :a && v.even? } # => { :b => 2 }

When you will not need the key or value in a filter block, the convention is to use an \_ in that place:

{ :a => 1, :b => 2, :c => 3 }.select { |_, v| v.even? } # => { :b => 2 }
{ :a => 1, :b => 2, :c => 3 }.select { |k, _| k == :c } # => { :c => 3 }

reject returns a new hash with key-value pairs for which the block evaluates to false:

{ :a => 1, :b => 2, :c => 3 }.reject { |_, v| v.even? } # => { :a => 1, :c => 3 }
{ :a => 1, :b => 2, :c => 3 }.reject { |k, _| k == :b } # => { :a => 1, :c => 3 }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents