Skip to content

Instantly share code, notes, and snippets.

@dasibre
Created September 1, 2013 20:33
Show Gist options
  • Save dasibre/6407117 to your computer and use it in GitHub Desktop.
Save dasibre/6407117 to your computer and use it in GitHub Desktop.
log = [
{time: 201201, x: 2},
{time: 201201, y: 7},
{time: 201201, z: 2},
{time: 201202, a: 3},
{time: 201202, b: 4},
{time: 201202, c: 0}
]
I want to collapse the array of hashes into this, all the hashes with the same time: should be merged into one.
[
{time: 201201, x: 2, y: 7, z: 2},
{time: 201202, a: 3, b: 4, c: 0},
]
My solution seems to work, but its functional, it wont work if another element is added to the array.
results = []
while log do
elt1 = log.select {|x| x[:time] == 201201 }
elt2 = log.select {|x| x[:time] == 201202 }
results << elt1[0].merge(elt1[1].merge(elt1[2]))
results << elt2[0].merge(elt2[1].merge(elt2[2]))
break
end
results
@DouweM
Copy link

DouweM commented Sep 1, 2013

log = [
  {time: 201201, x: 2},
  {time: 201201, y: 7},
  {time: 201201, z: 2},
  {time: 201202, a: 3},
  {time: 201202, b: 4},
  {time: 201202, c: 0}
]

log_hashes = Hash.new { |h, k| h[k] = { time: k } }
log.each do |log_line|
  log_hashes[log_line[:time]].merge!(log_line)
end

log = log_hashes.values
# End result: [{:time=>201201, :x=>2, :y=>7, :z=>2}, {:time=>201202, :a=>3, :b=>4, :c=>0}] 

@momer
Copy link

momer commented Sep 1, 2013

To get you started

a = log.select {|x| x[:time] == 201202}
x = {}
a.each { |arr| x.merge! arr }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment