合并哈希数组[ruby]

时间:2011-09-18 09:15:16

标签: ruby arrays hash merge

我有一系列哈希

[{:id=>2, :price_psm=>450, :rooms_count=>3, :sq=>50, :tax_inc=>"t", :title=>"title1"},
 {:id=>2, :price_psm=>499, :rooms_count=>3, :sq=>40, :tax_inc=>"t", :title=>"title1"}, 
 {:id=>2, :price_psm=>499, :rooms_count=>3, :sq=>41, :tax_inc=>"t", :title=>"title1"}, 
 {:id=>1, :price_psm=>450, :rooms_count=>2, :sq=>20, :tax_inc=>"t", :title=>"title2"}] 

我如何合并相同的哈希并创建这样的东西:

[{:id=>2, :price_psm=>[450,499,499], :rooms_count=>3, :sq=>[50,40,41], :tax_inc=>"t", :title=>"title1"}, 
 {:id=>1,  :price_psm=>450, :rooms_count=>2, :sq=>20, :tax_inc=>"t", :title=>"title2"}] 

2 个答案:

答案 0 :(得分:2)

类似的东西:

require 'pp'

INPUT = [{:id=>2, :price_psm=>450, :rooms_count=>3, :sq=>50, :tax_inc=>"t", :title=>"title1"},
        {:id=>2, :price_psm=>499, :rooms_count=>3, :sq=>40, :tax_inc=>"t", :title=>"title1"}, 
        {:id=>2, :price_psm=>499, :rooms_count=>3, :sq=>41, :tax_inc=>"t", :title=>"title1"}, 
        {:id=>1, :price_psm=>450, :rooms_count=>2, :sq=>20, :tax_inc=>"t", :title=>"title2"}] 



RES = INPUT.group_by {|row| row[:id] }.collect do |k,v|
  keys = v.collect {|rec| rec.keys}.flatten.uniq
  group = {}
  keys.each do |key|
    vals = v.collect { |rec| rec[key] }.uniq.compact
    group[key] = vals.size > 1 ? vals : vals.first
  end
  group
end

pp RES

答案 1 :(得分:1)

另一种功能方法(更短)

hashes.reduce do |a, b|
  a.merge(b) { |k, v1, v2| v1 == v2 ? v1 : [v1, v2].flatten }
end

#reduce将所有内容归为一个值,#merge将哈希对象合并在一起,并可以解决与您提供的块的合并冲突。

编辑|哎呀,抱歉,误读了所需的输出。这个做到了:

hashes.group_by { |hash| hash[:id] }.map do |id, hashes|
  hashes.reduce do |a, b|
    a.merge(b) { |key, v1, v2| v1 == v2 ? v1 : [v1, v2].flatten }
  end
end