File: sum.rb

package info (click to toggle)
ruby-powerpack 0.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 352 kB
  • sloc: ruby: 799; makefile: 3
file content (25 lines) | stat: -rw-r--r-- 690 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
unless Enumerable.method_defined? :sum
  module Enumerable
    # Sums up elements of a collection by invoking their `+` method.
    # Most useful for summing up numbers.
    #
    # @param initial [Object] an optional initial value.
    #   It defaults to 0 for an empty collection.
    # @return The sum of the elements, or the initial value if there
    #   are no elements.
    #
    # @example
    #   [1, 2, 3].sum #=> 6
    #   [[1], [2], [3]].sum #=> [1, 2, 3]
    #   [].sum #=> 0
    #   ["a"].sum #=> "a"
    #   ["b", "c"].sum("a") #=> "abc"
    def sum(initial = nil)
      if initial
        reduce(initial, &:+)
      else
        reduce(&:+) || 0
      end
    end
  end
end