2013-08-20 25 views
0

我正在試圖使頁面中的內容是來自兩個數組的數據。 我有兩個列表(陣列)與哈希: 如何有效地從json列表中接收紅寶石哈希

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" } ] 

頁,其中包括表結果數組,負荷非常緩慢,我需要找到產生result_array的最快方式。

請幫助我。

回答

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"}] 
+0

斯特凡,非常感謝 – bmalets

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 
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 
1
(arr1 + arr2).group_by { |i| i["device"] }.values.map{|x|x.reduce(&:merge)}