rails分组哈希数组

时间:2014-12-20 16:27:13

标签: ruby-on-rails arrays hash

我知道这是一个简单的问题,但它对我来说非常令人沮丧,我尝试了很多时间而且我没有做到,所以我希望能找到答案,

我有像这样的哈希数组

array = [{date: 1, branch: 1, value: "100"}, {date: 1, branch: 2, value: "200"}, {date: 2, branch: 1, value: "500"}, {date: 3, branch: 2, value: "500"}, {date: 3, branch: 3, value: "300"}]

我希望像这样分组

data = [{date: 1, 1: "100", 2: "200"}, {date: 2, 1: "500"}, {date: 3, 2: "500", 3: "300"}]
数组中的

= [{date:1,branch:1,value:“100”},我想取分支和值的值并将其合并为1:“100”

无论如何我可以这样做,如果在方法

时使用循环或大小写没有问题

2 个答案:

答案 0 :(得分:3)

可能会缩短,但它有效:

array.group_by { |h| h[:date] }.map do |k, v|
  [:date, k, *v.map { |h| [h[:branch], h[:value]] }]
end.map { |x| Hash[*x.flatten] }
# => [{:date=>1, 1=>"100", 2=>"200"}, {:date=>2, 1=>"500"}, {:date=>3, 2=>"500", 3=>"300"}]

答案 1 :(得分:1)

另一种解决方案

array = [{date: 1, branch: 1, value: "100"}, {date: 1, branch: 2, value: "200"}, {date: 2, branch: 1, value: "500"}, {date: 3, branch: 2, value: "500"}, {date: 3, branch: 3, value: "300"}]
data = array.inject({}) do |res, val| 

  if res[val[:date]]
    res[val[:date]].merge!({val[:branch] => val[:value]})
  else 
    res.merge!(val[:date] => {val[:branch] => val[:value]})
  end  
  res  
end
puts data.collect{|key, val| {date: key}.merge!(val)}