Folding: reduce and each_with_object
sum adds a whole list up into one number, max_by picks one winner out of it. Both fold a list into a single value. But what if Ruby has no ready-made method for the fold you need? Then you write it yourself. The plain way first: a variable that carries the result along while each walks through the list – here Chunky counts his bites of bacon:
bites = [3, 5, 2, 4]
total = 0
bites.each do |n|
total = total + n
end
totalA start value, then every element changes the running value – this pattern is so common that it has a name of its own: reduce. You hand it the start value; the block gets the running value (the accumulator, here sum) and the next element, and whatever the block returns becomes the new accumulator. No variable outside the block needed. Step through with ⏯ and watch sum grow – 0, 3, 8, 10 – until 14 comes out:
bites.reduce(0) do |sum, n|
sum + n
endWhen the block does nothing but apply one operator, hand reduce the operator's name as a symbol: reduce(:+) adds, reduce(:*) multiplies. Without a start value, reduce simply starts with the first element. And inject is the very same method under its older name – you will meet both:
p bites.reduce(:+)
p (1..5).reduce(:*) # 1 * 2 * 3 * 4 * 5
[2, 3, 4].inject(:*)The accumulator doesn't have to be a number – it can be anything. Here it is the longest word so far: in every round the block keeps whichever of the two words is longer. That is roughly how max_by works inside:
words = %w[egg bacon toast pancake jam]
words.reduce do |longest, word|
word.length > longest.length ? word : longest
endNow the classic mistake. Whatever the last line of the block returns becomes the new accumulator – so what happens when Chunky puts a puts at the end, to watch?
bites.reduce(0) do |sum, n|
sum + n
puts "so far: #{sum}"
endA NoMethodError: undefined method '+' for nil. In the first round sum + n was worked out – and thrown away, because puts came last, and puts returns nil. So in the second round sum was nil, and nil can't add. An if without else on the last line does the same whenever its condition is false. The rule: the new accumulator goes on the block's last line. Here is the repaired version – puts first, the sum last:
bites.reduce(0) do |sum, n|
puts "so far: #{sum}, now #{n}"
sum + n
endOften the result is a hash or an array that you fill bit by bit. You can do that with reduce, but then every round must end with the hash again – easy to forget, and now you know what happens then. each_with_object is made for this: you hand it the empty object, the block fills it, and at the end the method returns the object, whatever the block's last line was. Mind the order of the block's parameters – the element first, then the object. The kitchen adds up the orders:
orders = [
{ food: "bacon", amount: 2 },
{ food: "egg", amount: 1 },
{ food: "bacon", amount: 3 }
]
orders.each_with_object(Hash.new(0)) do |order, per_food|
per_food[order[:food]] += order[:amount]
endWith an empty array, each_with_object([]) collects – and unlike with map, one element may add several entries, or none at all. The waiter puts every single plate on the tray:
orders.each_with_object([]) do |order, tray|
order[:amount].times { tray << order[:food] }
endA rule of thumb: if a ready-made method does the fold – sum, max_by, tally – take it. If not, take reduce when the result is one value that changes from round to round, and each_with_object when you fill a hash or an array. With reduce, the new value always goes on the last line.
events into energy with reduce: add each change, and after every step keep the result within 0..100 – with clamp from lesson 9. (Simply adding everything up would give 75 – but at 100 Chunky is full, however much bacon is left.)# bacon, more bacon, a long run, a nap, supper
events = [30, 40, -90, 20, 25]
# energy = ... # in the evening: start at 50, stay within 0 to 100
recipes says what each dish needs, week what she is going to cook. Build the hash shopping with each_with_object: every ingredient and how much of it the whole week needs – { "egg" => 7, … }.recipes = {
"pancakes" => { "egg" => 2, "milk" => 3, "flour" => 2 },
"omelette" => { "egg" => 3, "cheese" => 1 }
}
week = ["pancakes", "omelette", "pancakes"]
# shopping = ... # every ingredient => how much the week needs