如何计算数组元素的运行总数?

时间:2021-07-18 08:52:20

I'm working in Rails 3.1 as a relative noob, and have managed to extract user Transaction amounts from the db into a date-ordered array using this code (where date and amount_cents are db attributes):

我在Rails 3.1中作为相对noob工​​作,并设法使用此代码将db中的用户事务量提取到日期排序的数组中(其中date和amount_cents是db属性):

@user_trans = User.transactions.order("date").map {|t| t.amount_cents}

@user_trans = User.transactions.order(“date”)。map {| t | t.amount_cents}

=> [1000, -350, -250, 600, 750, -450]

=> [1000,-350,-250,600,750,-450]

I easily get a total of the array with:

我很容易得到一个数组:

@user_trans.sum => 1300

@ user_trans.sum => 1300

But what I just can't figure out is an elegant way to iterate over each element of the array and add the first element to the second, second to third, etc., resulting in running totals:

但我无法弄清楚的是迭代数组的每个元素并将第一个元素添加到第二个,第二个到第三个等的优雅方式,从而导致运行总计:

[1000, 650, 400, 1000, 1750, 1300]

[1000,650,400,1000,1750,1300]

It seems that .each or .inject would be the method used, but outside of a clunky multi-line hack, I haven't found the magic syntax to do this, but it seems there should be a streamlined approach. Order IS important. Maybe regress off the total, then reverse?

似乎.each或.inject将是使用的方法,但在笨重的多行黑客之外,我还没有找到执行此操作的神奇语法,但似乎应该采用简化的方法。订单很重要。也许退回总数,然后反转?

I sit at your feet with hopeful expectation... :)

我满怀期待地坐在你的脚边...... :)

1 个解决方案

#1


4  

Here's a one-liner. The to_i is necessary to handle the first element where the result array is empty (nil.to_i will evaluate to 0).

这是一个单行。 to_i是处理结果数组为空的第一个元素所必需的(nil.to_i将计算为0)。

@user_trans.inject([]) { |result, element| result << result.last.to_i + element }

#1


4  

Here's a one-liner. The to_i is necessary to handle the first element where the result array is empty (nil.to_i will evaluate to 0).

这是一个单行。 to_i是处理结果数组为空的第一个元素所必需的(nil.to_i将计算为0)。

@user_trans.inject([]) { |result, element| result << result.last.to_i + element }