code-gijoe
code-gijoe

Reputation: 7244

How can I get the values of hash using a key array?

I want to get all value of a hash using an array containing the keys?

I have this hash:

{:id=>402, :email=>"[email protected]", :organizations_count=>0, :username=>"admin"}

I have an array :

[:id, :email]

So I want to get an array of

["402", "[email protected]"]

Is there a cleaver way to do this? I have a loop but I feel ruby can do this in a "oneliner" way but can figure out how to do this.

Upvotes: 0

Views: 40

Answers (1)

Ilya
Ilya

Reputation: 13487

You should use Hash#values_at:

hash = {:id=>402, :email=>"[email protected]", :organizations_count=>0, :username=>"admin"}
array = [:id, :email]
hash.values_at(*array)
#=> [402, "[email protected]"]

Passing array with splat operator (*) as argument in this case is same as just hash.values_at(:id, :email)

Upvotes: 2

Related Questions