如何有效地加入从json列表中收到的ruby哈希值

时间:2013-08-20 16:48:02

标签: ruby arrays algorithm sorting hash

我正在尝试使用表格来制作页面,其内容是来自两个数组的数据。 我有两个带散列的列表(数组):

arr1 = [ 
         { "device"=>100, "phone"=>"12345" }, 
         ..., 
         { "device"=>102, "phone"=>"12346" } 
       ]


arr2 = [ 
         { "device"=>100, "type"=>"mobile", "name"=>"nokia" }, 
         ..., 
         { "device"=>102, "type"=>"VIOP", "name"=>"smth" } 
       ]

How can I join hashes from arr1 and arr2 by "device" to get a result array:

result = [ 
           { "device"=>100, "phone"=>"12345", "type"=>"mobile", "name"=>"nokia" }, 
           ..., 
           { "device"=>102, "phone"=>"12346", "type"=>"VIOP", "name"=>"smth" } 
         ]

arr1 = [ { "device"=>100, "phone"=>"12345" }, ..., { "device"=>102, "phone"=>"12346" } ] arr2 = [ { "device"=>100, "type"=>"mobile", "name"=>"nokia" }, ..., { "device"=>102, "type"=>"VIOP", "name"=>"smth" } ]

包含结果数组表的页面,加载速度非常慢,我需要找到生成result_array的最快方法。

请帮帮我。

4 个答案:

答案 0 :(得分:2)

这样可行:

(arr1 + arr2).group_by { |i| i["device"] }.map { |d,(i1,i2)| i1.merge(i2)}
#=> [{"device"=>100, "phone"=>"12345", "type"=>"mobile", "name"=>"nokia"}, {"device"=>102, "phone"=>"12346", "type"=>"VIOP", "name"=>"smth"}]

答案 1 :(得分:1)

解决这个问题的多种方法。这是一种非常易读的方法:

# prepare an index hash for easier access of data by device
first_by_device = arr1.group_by {|a| a['device'] }

# build a new array joining both data hashes for each item
result = arr2.map do |item|
  device = item['device']
  item.merge first_by_device(device)
end

答案 2 :(得分:1)

(arr1 + arr2).group_by { |i| i["device"] }.values.map{|x|x.reduce(&:merge)}

答案 3 :(得分:0)

也许它不是最漂亮的,但它确实有效:

result = arr1.collect{|a| h = arr2.select{|b| b["device"] ==
a["device"]}.first; h ? a.merge(h) : a }

对于大量数据,您是否需要更快的东西?

h = Hash.new
arr1.each do |a|
  h[ a["device" ] ] ||= Hash.new
  h[ a["device" ] ].merge!(a)
end
arr2.each do |a|
  h[ a["device" ] ] ||= Hash.new
  h[ a["device" ] ].merge!(a)
end
result = h.values