Does Rails concatenate two hash arrays?

I find it difficult to understand the logic with which I need to combine two hash arrays. It seems I asked a question < his question a while ago in a different way, I also tried several other things, such as the answers suggested here: merging hash arrays

Any help on this will help me.

Let's say I have the following array, and this is inferred from the method itself, so you can imagine that there :timestampwill be Timeobjects

[
  {:timestamp=>2011-12-19 00:00:00 UTC},
  {:timestamp=>2011-12-19 01:00:00 UTC},
  {:timestamp=>2011-12-19 02:00:00 UTC},
  {:timestamp=>2011-12-19 03:00:00 UTC},
  {:timestamp=>2011-12-19 04:00:00 UTC},
  {:timestamp=>2011-12-19 05:00:00 UTC}
]

And then an additional array like this, each of which has a different value (but sometimes it can have even more values ​​besides :count)

[
  {:timestamp=>2011-12-19 02:00:00 UTC, :count=>5},
  {:timestamp=>2011-12-19 04:00:00 UTC, :count=>21}
]

And you get something like this:

[
  {:timestamp=>2011-12-19 00:00:00 UTC},
  {:timestamp=>2011-12-19 01:00:00 UTC},
  {:timestamp=>2011-12-19 02:00:00 UTC, :count=>5},
  {:timestamp=>2011-12-19 03:00:00 UTC},
  {:timestamp=>2011-12-19 04:00:00 UTC, :count=>21},
  {:timestamp=>2011-12-19 05:00:00 UTC}
]

, , , .

+5
3

, :

(a1+a2).group_by{|h| h[:timestamp]}.map{|k,v| v.reduce(:merge)}
+23
a = [
  {:timestamp=>'2011-12-19 00:00:00 UTC'},
  {:timestamp=>'2011-12-19 01:00:00 UTC'},
  {:timestamp=>'2011-12-19 02:00:00 UTC'},
  {:timestamp=>'2011-12-19 03:00:00 UTC'},
  {:timestamp=>'2011-12-19 04:00:00 UTC'},
  {:timestamp=>'2011-12-19 05:00:00 UTC'}
]

b = [
  {:timestamp=>'2011-12-19 02:00:00 UTC', :count=>5},
  {:timestamp=>'2011-12-19 04:00:00 UTC', :count=>21}
]

result = a.inject([]) do |memo, v|
  if match = b.detect { |w| (w.to_a & v.to_a).any? }
    memo << match.merge(v)
  else
    memo << v
  end
end

p result
+2

:timestamp "", :timestamp :

h1 = Hash[a1.map{|h| [h[:timestamp], h]}]
h2 = Hash[a2.map{|h| [h[:timestamp], h]}]

, , merge - ( ):

p h1.merge(h2).values
# => [
#  {:timestamp=>"2011-12-19 00:00:00 UTC"},
#  {:timestamp=>"2011-12-19 01:00:00 UTC"},
#  {:timestamp=>"2011-12-19 02:00:00 UTC", :count=>5},
#  {:timestamp=>"2011-12-19 03:00:00 UTC"},
#  {:timestamp=>"2011-12-19 04:00:00 UTC", :count=>21},
#  {:timestamp=>"2011-12-19 05:00:00 UTC"}
#]
+2

All Articles