如何在数组中选择匿名哈希?

时间:2014-03-22 21:17:05

标签: ruby arrays select hash

我有以下数组,我想选择每个键:

names = [
 {"Ánias"=>{:gender=>"male", :nationality=>"faroese"}},
 {"Annfinnur"=>{:gender=>"male", :nationality=>"faroese"}},
 {"Ansgar"=>{:gender=>"male", :nationality=>"faroese"}}
]

我如何选择所有名字(“Ánias”,“Annfinnur”,“Ansgar”)?

1 个答案:

答案 0 :(得分:2)

只做

names = [
          {"Ánias"=>{:gender=>"male", :nationality=>"faroese"}},
          {"Annfinnur"=>{:gender=>"male", :nationality=>"faroese"}},
          {"Ansgar"=>{:gender=>"male", :nationality=>"faroese"}}
        ]

names.map { |h| h.keys.first }
# => ["Ánias", "Annfinnur", "Ansgar"]