N. Semenov N. Semenov - 1 year ago 52
Ruby Question

Getting an array for chart

I had 10 items in total. I lost all of them in 3 days: 5 items on the 1st day, 3 items on the 2nd day, and 2 items on the last day. I need to get an array

[5, 2, 0]
of remaining items at the end of each day. How can I get the array, given total
10
and the array of lost items
[5, 3, 2]
?

Answer Source
[5, 3, 2].each_with_object([10]){|e, a| a.push(a.last - e)}.drop(1)
# => [5, 2, 0]

Know why you need the complication drop(1)? It is because, without it, the answer makes more logical sense. Your requirement is what was complicated.

[5, 3, 2].each_with_object([10]){|e, a| a.push(a.last - e)}
# => [10, 5, 2, 0]

The initial 10 represents the initial state.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download