File: sum.rb

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