harshs08 harshs08 - 7 months ago 17
Ruby Question

Select key value pairs from a hash whose keys belong to an array

I have an array of keys:

keys = ["first_name", "last_name", "foo"]

and a hash:

hsh = {"first_name" => "tester", "zoo" => "loo", "foo" => "bar"}

I want to extract the key-value pairs whose keys are present in the array, to get:

res = {"first_name" => "tester", "foo" => "bar"}

Is there a way to do this?


Try this:

hsh.select{ |k, v| keys.include?(k) }