harshs08 harshs08 - 1 year ago 40
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?

Answer Source

Try this:

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