4 ms·
Yeah, but remember to pass the 0 to it; otherwise the sum of an empty array would be nil: x.inject(0, &:+) That's one of the disadvantages of not having a p
by epidemian 13y ago
Yeah, but remember to pass the 0 to it; otherwise the sum of an empty array would be nil:
x.inject(0, &:+)
That's one of the disadvantages of not having a powerful type system to infer what's the "zero" of some type.
Still, the Ruby code is pretty readable and a good example of orthogonal concepts that compose well. E.g., getting the product of the numbers instead: x.inject(1, &:*). Or the least common multiple: x.inject(&:lcm).