stellard stellard - 21 days ago 4x
Ruby Question

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.


Maybe this it what you want.

wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"} { |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.