Ruby 使用特定键散列到另一个散列

Ruby hash to another hash with certain keys

我有这样的散列

[{"user_id"=>"4672046155508aafb4d01bca27cca8c6", "email"=>"xxxxxxxxxx@gmail.com", "sport"=>[nil]}, {"user_id"=>"007ba6fd74b3ef3c12734ddd0f2280ae", "email"=>"xxxxxxxx@yahoo.com", "sport"=>[nil, nil, nil, nil]}, {"user_id"=>"0085e4d74738a384e10042b62acb56e2", "email"=>"xxxxxxxxxx@gmail.com", "sport"=>[nil, nil, nil]}]

我需要一个包含所有电子邮件的散列,该怎么做?...每当我使用

  users[:email]

报错cannot convert symbol to integer

你可以这样做

hash_array = [{"user_id"=>"4672046155508aafb4d01bca27cca8c6", "email"=>"xxxxxxxxxx@gmail.com", "sport"=>[nil]}, {"user_id"=>"007ba6fd74b3ef3c12734ddd0f2280ae", "email"=>"xxxxxxxx@yahoo.com", "sport"=>[nil, nil, nil, nil]}, {"user_id"=>"0085e4d74738a384e10042b62acb56e2", "email"=>"xxxxxxxxxx@gmail.com", "sport"=>[nil, nil, nil]}]
hash_array.map{ |hash| hash["email"] }

它将return所有电子邮件的数组

它不是哈希,它是一个哈希数组。要访问第一个哈希值 email,您可以这样做:

users.first['email']