Navin
Navin

Reputation: 646

Ruby hash to another hash with certain keys

I have a hash like this

[{"user_id"=>"4672046155508aafb4d01bca27cca8c6", "email"=>"[email protected]", "sport"=>[nil]}, {"user_id"=>"007ba6fd74b3ef3c12734ddd0f2280ae", "email"=>"[email protected]", "sport"=>[nil, nil, nil, nil]}, {"user_id"=>"0085e4d74738a384e10042b62acb56e2", "email"=>"[email protected]", "sport"=>[nil, nil, nil]}]

I need a hash with all email in it , How to do this?...whenever I use

  users[:email]

It gives the error cannot convert symbol to integer

Upvotes: 0

Views: 130

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do like this

hash_array = [{"user_id"=>"4672046155508aafb4d01bca27cca8c6", "email"=>"[email protected]", "sport"=>[nil]}, {"user_id"=>"007ba6fd74b3ef3c12734ddd0f2280ae", "email"=>"[email protected]", "sport"=>[nil, nil, nil, nil]}, {"user_id"=>"0085e4d74738a384e10042b62acb56e2", "email"=>"[email protected]", "sport"=>[nil, nil, nil]}]
hash_array.map{ |hash| hash["email"] }

It will return an array of all the emails

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51151

It isn't hash, it's an array of hashes. To access first hash email, you can do:

users.first['email']

Upvotes: 0

Related Questions