Take me home

Filter hashes by keys

Written by August Lilleaas, published November 22, 2007

Hash + enumerable = annoying, but negative rejects lets you achieve this filtering thingie.

I find the enumerable stuff in hash annoying. Hash#select returns arrays and stuff, I hate it.

I needed to filter a hash by keys.

h = {:hai => "lolz", :burz => "barz", :maz => "garfer"}
puts h.filter(:hai, :burz)
# => {:hai=>"lolz", :burz=>"barz"}

.reject was the only enumerable thingie I found that returned a hash and isn’t destructive (such as delete_all), so this is what I ended up doing:

class Hash
  def filter(*args)
    reject {|k, v| !args.include?(k) }
  end
end

Works well.


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.