Martin
Martin

Reputation: 11336

How to sum an array of hashes to an array in ruby

Is there a simpler way to do this?

What I try to do here is simply add the item hashes inside each list to myarray

myarray = []
list = [{list: [{item: 'item1'},{item: 'item2'}]}, {list: [{item: 'item3'},{item: 'item4'}]}, {list: [{item: 'item5'},{item: 'item6'}]}]

list.each do |list| 
  myarray = myarray + list
end

Upvotes: 0

Views: 78

Answers (1)

Diego Basch
Diego Basch

Reputation: 13069

This:

((list.map {|x| x[:list]}).flatten).map{|x| x[:item] if x != nil}

produces this:

["item1", "item2", "item3", "item4", nil] 

(the nil is because your last element is

{item: [{item: 'item5'},{item: 'item6'}]}

I assume you meant list: just like in the others.

Upvotes: 1

Related Questions