tags:

views:

1512

answers:

5
+6  Q: 

Ruby Hash Filter

Hello

I am trying to figure out how I can filter out key and value pairs from one filter into another

For example I want to take this hash

x = { "one" => "one", "two" => "two", "three" => "three"}

y = x.some_function

y = { "one" => "one", "two" => "two"}

Thanks for your help

+10  A: 

You can just use the built in Hash function reject.

x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.reject {|key,value| key == "three" }
y == { "one" => "one", "two" => "two"}

You can put whatever logic you want into the reject, and if the block returns true it will skip that key,value in the new hash.

ScottD
5 seconds behind on the typing... I knew I should have posted before testing to make sure I didn't make a typo.
Brian Campbell
You can use `reject!` rather than setting another variable
Ryan Bigg
@Radar Destructive modifiers can cause problems, if for instance the hash is being passed in as an argument to a method and the caller does not expect the hash to be modified by that method. Best to be in the habit of doing non-destructive updates, and only use destructive operators when necessary.
Brian Campbell
This is good however I may not know the other hash keys. I only know the ones that I want
rube_noob
+5  A: 
y = x.reject {|k,v| k == "three"}
Brian Campbell
+2  A: 

Maybe this it what you want.

wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }

The Enumerable mixin which is included in e.g. Array and Hash provides a lot of useful methods like select/reject/each/etc.. I suggest that you take a look at the documentation for it with ri Enumerable.

sris
but the select method returns an array. In this case I need a hash
rube_noob
Ah, sorry, missed that bit.
sris
+2  A: 

Using a combination of everyones answers I have come up with this solution

 wanted_keys = %w[one two]
 x = { "one" => "one", "two" => "two", "three" => "three"}
 x.reject { |key,_| !wanted_keys.include? key }
 =>{ "one" => "one", "two" => "two"}

Thanks for your help guys!

rube_noob
+4  A: 

Rails' ActiveSupport library also gives you slice and except for dealing with the hash on a key level:

y = x.slice("one", "two") # => { "one" => "one", "two" => "three" }
y = x.except("three")     # => { "one" => "one", "two" => "three" }
x.slice!("one", "two")    # x is now { "one" => "one", "two" => "three" }

These are quite nice, and I use them all the time.

Brian Guthrie