ruby on Rails: Merge 2 activerecord arrays
I Have 2 arrays such as:
arr1 : {[:day => 12, :sum_src => 1234], [:day => 14, :sum_src => 24543]}
arr2 : {[:day => 12, :sum_dst => 4234], [:day => 14, :sum_dst => 342334]}
I want to merge this two arrays in开发者_JS百科to one, so that it looks like:
arr3 : {[:day => 12, :sum_src => 1234, :sum_dst => 4234],[:day => 14, :sum_src => 24543, :sum_dst => 342334]}
Is it possible? And how to do this ?
Riffing off Qerub's answer - if the arrays are sorted as in the example zip can be a great tool for this:
arr1 = [{:day => 12, :sum_src => 1234}, {:day => 14, :sum_src => 24543}]
arr2 = [{:day => 12, :sum_dst => 4234}, {:day => 14, :sum_dst => 342334}]
arr1.zip(arr2).map {|a,b| a.merge!(b)}
Result
[{:day=>12, :sum_dst=>4234, :sum_src=>1234}, {:day=>14, :sum_dst=>342334, :sum_src=>24543}]
Like Omar pointed out, those are hashes. If you have two hashes:
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
In your case, if you want to merge to arrays and remove repetitions, I would use Union operator:
[ "a", "b", "c" ] | [ "c", "d", "a" ] #=> [ "a", "b", "c", "d" ]
Taken from Rails API. Good luck!
(You have mixed up the syntaxes for literal hashes and arrays, but anyway…)
Here's a short but slightly cryptic solution:
arr1 = [{:day => 12, :sum_src => 1234}, {:day => 14, :sum_src => 24543}]
arr2 = [{:day => 12, :sum_dst => 4234}, {:day => 14, :sum_dst => 342334}]
result = (arr1 + arr2).inject({}) { |mem, x|
(mem[x[:day]] ||= {}).merge!(x); mem
}.values
Result:
[{:sum_dst=>4234, :day=>12, :sum_src=>1234}, {:sum_dst=>342334, :day=>14, :sum_src=>24543}]
A more readable version would probably have more explicit looping. (Left for the reader as an exercise.)
精彩评论