使用哈希格式化数组

时间:2014-04-25 09:23:29

标签: ruby-on-rails ruby arrays ruby-on-rails-4

我必须得到像这样的数组

 [{"social"=>"linkedin", "count"=>1},
 {"social"=>"twitter",   "count"=>1}, 
 {"social"=>"facebook",  "count"=>0}]

来自这个数组

=> [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}]

我怎么做?

2 个答案:

答案 0 :(得分:11)

您可以尝试:

arr = [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}]

arr[0].map { |key, value| {'social' => key, 'count'=>value } }
# => [{"soсial"=>"twitter", "count"=>1}, {"soсial"=>"linkedin", "count"=>1}, {"soсial"=>"facebook", "count"=>0}]

答案 1 :(得分:0)

如下所示:

[{"twitter"=>1, "linkedin"=>1, "facebook"=>0}].first.to_a.map do |a|
  { "sotial" => a[0], "count" => a[1] } 
end