Ruby Hash Whitelist Filter
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
EDIT: should probably mention that in this example, I want it to behave as a whitelist filter. That is, I know what I want, not what I don't want.
Solution 1:
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" => "two" }
y = x.except("three") # => { "one" => "one", "two" => "two" }
x.slice!("one", "two") # x is now { "one" => "one", "two" => "two" }
These are quite nice, and I use them all the time.
Solution 2:
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.
Solution 3:
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.
Solution 4:
Improving a bit @scottd answer, if you are using rails and have a list of what you need, you can expand the list as parameters from slice. For example
hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
hash.slice(*keys_whitelist)
And without rails, for any ruby version, you can do the following:
hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
Hash[hash.find_all{|k,v| keys_whitelist.include?(k)}]