typestar

reduce in Ruby

Folding a collection into one value, from sums to custom picks.

nums = [3, 7, 2, 9, 4]

puts nums.reduce(:+)
puts nums.reduce(1) { |product, n| product * n }

longest = %w[cat horse ox].reduce do |best, w|
  w.length > best.length ? w : best
end
puts longest

# each_with_object carries the accumulator without returning it each pass
index = %w[ruby gem rake].each_with_object({}) { |w, h| h[w[0]] = w }
puts index.inspect

How it works

  1. reduce(:+) folds with an operator and no block at all.
  2. A seed value starts the fold; the block returns each new total.
  3. each_with_object carries a hash through without returning it.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
356
Tokens
96
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 3 of 3 in Blocks & iterators, step 12 of 29 in Language basics.

← Previous Next →