Inject/Reduce doesn’t work on lists of ActiveRecords

Problem:

The following line of code for calculating the total order cost returns “#”.

@purchase_items.reduce() {|cost, item| cost += item.qty_ordered * item.unit_price }

Cause:

The default memo item for a reduce operation in Ruby is the first item on the list (because of this, it starts the reduce on the second item).

Solution:

You can set the initial memo item by passing it to the reduce function.

@purchase_items.reduce(0) {|cost, item| cost += item.qty_ordered * item.unit_price }

Leave a Reply