2013-05-16 169 views
1

我有散列的數組,像這樣:從哈希數組中提取鍵值?

[ 
    {"name"=>"Bob Jones", "id"=>"100005913544738"}, 
    {"name"=>"Jimmy Smith", "id"=>"100005934513815"}, 
    {"name"=>"Abe Lincoln", "id"=>"100005954493955"} 
] 

我最終只是希望這些ID在一個數組,像這樣:

[ 100005913544738, 100005934513815, 100005954493955 ] 

我跑的Ruby 1.9.3。

回答

7
a = [{"name"=>"Bob Jones", "id"=>"100005913544738"}, 
    {"name"=>"Jimmy Smith", "id"=>"100005934513815"}, 
    {"name"=>"Abe Lincoln", "id"=>"100005954493955"}] 

a.map{|h| h['id'].to_i} 
# => [100005913544738, 100005934513815, 100005954493955] 

Enumerable#map是一個非常方便熟悉的方法。

似乎值得注意的是,如果您可以控制原始數組的生成,那麼使用符號(例如,:name:id)而不是字符串作爲哈希鍵更像Ruby。這裏有many reasons

0
h = [ 
    {"name"=>"Bob Jones", "id"=>"100005913544738"}, 
    {"name"=>"Jimmy Smith", "id"=>"100005934513815"}, 
    {"name"=>"Abe Lincoln", "id"=>"100005954493955"} 
] 

h.map{|i| i.fetch("id").to_i} 
#=> [100005913544738, 100005934513815, 100005954493955]