how can iterate over an array of array of hashes in ruby -


i have list below:

order = [   {term: 201, x: 2},   {term: 201, y: 7},   {term: 201, z: 2},   {term: 202, a: 3},   {term: 202, b: 4},   {term: 202, c: 0} ] 

how can result?

[   {term: 201, x: 2, y: 7, z: 2},   {term: 202, a: 3, b: 4, c: 0}, ] 

you can use group_by method :

order.group_by { |h| h[:term] }      .map { |_, v| v.inject(:update) } # => [{:term=>201, :x=>2, :y=>7, :z=>2}, {:term=>202, :a=>3, :b=>4, :c=>0}] 
  • group small hashes term number.

  • then iterate on each group of small hashes.

  • while iterating merge small hashes make single one.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -