Ruby example

How to sum an array in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Call sum on the array: [4, 8, 15].sum returns 27, and an empty array sums to 0. To add up a field, pass a block: cart.sum { |i| i.price * i.qty } or cart.sum(&:price). For the smallest and largest values, use min, max or minmax, and max_by to pick an element by one of its fields.

In Ruby, sum is a method on the array (and on any Enumerable), not a function you pass the array to as in Python. It has been there since Ruby 2.4, so the inject(:+) you see in older Stack Overflow answers is no longer needed, and it differs in two ways that matter: empty arrays and floats. The sections below cover sum itself, summing a field of objects or hashes, what changes with inject and with strings, an average without integer division, min, max and their _by versions, and totals per group, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Array#sumRecommended

array.sum adds the elements with +, starting from 0. That start value is why an empty array gives 0 rather than nil. The result has the type the numbers lead to: integers give an Integer, one Float makes the whole sum a Float, and sum(0.0) asks for a Float from the start. With a block, sum adds the block's value for each element instead of the element, so there is no need for a map first. Every element must be a number (or something the block turns into one): nil raises a TypeError, so drop it with compact.

sum.rb
numbers = [4, 8, 15, 16, 23, 42]
p numbers.sum

# An empty array sums to 0, not nil
p [].sum

# Floats in, Float out; sum(0.0) forces a Float
p [1.5, 2.25, 3].sum
p [1, 2, 3].sum(0.0)

# A block sums a value computed from each element
p numbers.sum { |n| n * n }

# Ranges and other Enumerables have sum too
p (1..100).sum

# Strings in an array: convert first, or sum in the block
p ["10", "20", "5"].sum(&:to_i)

# nil in the array raises; compact drops it first
scores = [7, nil, 9]
p scores.compact.sum

Output

The six numbers add up to 108, and [].sum prints 0. Mixing 3 with floats gives 6.75, and sum(0.0) turns the integer total into 6.0. The block version adds the squares (2854) without building a temporary array. &:to_i is shorthand for { |s| s.to_i }, so the strings add up to 35. Without compact, [7, nil, 9].sum stops with TypeError: nil can't be coerced into Integer.

2Sum a field of objects, hashes or a hash

To total one attribute of each object, pass it as &:price; when the value needs a calculation, such as price times quantity, write the block out. For an array of hashes, read the key inside the block. To sum only some elements, filter with select first or return 0 from the block for the ones you skip. A Hash is also an Enumerable: sum its values, or pass a block that receives each key and value.

sum_a_field.rb
Item = Struct.new(:name, :price, :qty)

cart = [
  Item.new("pen", 1.5, 4),
  Item.new("notebook", 3.25, 2),
  Item.new("bag", 24.0, 1)
]

# Sum one attribute
p cart.sum(&:price)

# Sum a computed value: price times quantity
p cart.sum { |i| i.price * i.qty }

# Array of hashes: it is the block's implicit parameter
orders = [{ id: 1, qty: 3 }, { id: 2, qty: 5 }, { id: 3, qty: 2 }]
p orders.sum { it[:qty] }

# Only some elements: filter first, or use a condition
p orders.sum { |o| o[:qty] > 2 ? o[:qty] : 0 }
p orders.select { |o| o[:id].odd? }.sum { |o| o[:qty] }

# A hash's values
stock = { apples: 12, pears: 7, plums: 30 }
p stock.values.sum
p stock.sum { |_fruit, count| count }

Output

The prices add up to 28.75 and the line totals to 36.5. The hashes give 10 for all quantities, 8 when only those above 2 count, and 5 for the orders with odd ids. Both hash lines print 49; the underscore in _fruit marks a block parameter you do not use. The it parameter is Ruby 3.4 and later; on older versions name it, as in { |o| o[:qty] }. Rails also has sum(:price) on ActiveRecord relations, which sums in the database; that is a Rails method, not the Ruby one shown here.

3inject(:+), float accuracy and strings

Answers written before Ruby 2.4 use inject(:+) (reduce is the same method). It still works, with two differences. Without a start value it returns nil for an empty array (JavaScript's reduce throws there instead), so old code writes reduce(0, :+). And for floats, sum uses the Kahan-Babuska compensated summation, which keeps the rounding error of each addition and corrects for it, while inject just adds one float at a time. sum starts at 0, so summing strings or arrays needs a start value of the same type.

inject_and_floats.rb
# What older answers use: inject (alias reduce)
p [1, 2, 3].inject(:+)
p [1, 2, 3].reduce(0) { |total, n| total + n }

# The trap: no start value means nil for an empty array
p [].inject(:+)
p [].reduce(0, :+)
p [].sum

# Floats: sum compensates for rounding error, + does not
prices = [0.1, 0.2, 0.3]
p prices.sum
p prices.inject(:+)
p ([0.1] * 10).sum
p ([0.1] * 10).inject(:+)

# Strings: sum starts at 0, so give it "" (or use join)
words = ["ab", "cd", "ef"]
p words.sum("")
p words.join
begin
  words.sum
rescue TypeError => e
  puts "TypeError: #{e.message}"
end

# Arrays: sum([]) concatenates, flatten(1) does the same
p [[1, 2], [3], [4, 5]].sum([])

Output

[].inject(:+) prints nil, so a later + 1 or / size would crash; reduce(0, :+) and sum both give 0. For the floats, sum prints 0.6 and 1.0 where inject prints 0.6000000000000001 and 0.9999999999999999. That makes sum more accurate, not exact: a binary float can't hold 0.1, so for money use integer cents or BigDecimal. For strings, join is the usual choice; sum without "" raises String can't be coerced into Integer because it tries 0 + "ab".

4Average: sum.fdiv(size)

Ruby has no mean or average method; divide the sum by the size. The catch is that dividing an Integer by an Integer is integer division, which drops the fraction, so 7 / 2 is 3 (Python's //, not its /). Use fdiv, which always returns a Float, or convert one side with to_f. Decide what an empty array should give before you divide: fdiv returns NaN and / raises.

average.rb
marks = [7, 8, 8, 6]

# Integer / Integer drops the fraction
p marks.sum / marks.size
p 7 / 2

# fdiv returns a Float
p marks.sum.fdiv(marks.size)
p (marks.sum.to_f / marks.size).round(1)

# An empty array: 0.fdiv(0) is NaN, 0 / 0 raises
p [].sum.fdiv([].size)
begin
  [].sum / [].size
rescue ZeroDivisionError => e
  puts "ZeroDivisionError: #{e.message}"
end

def average(values)
  return nil if values.empty?

  values.sum.fdiv(values.size)
end

p average([3, 4, 4])
p average([])

# Exact result with Rational
p marks.sum.quo(marks.size)

Output

The marks average 7.25, but sum / size prints 7 with no warning. round(1) gives 7.3 for display. On an empty array fdiv prints NaN and the integer version raises ZeroDivisionError: divided by 0, so the average helper returns nil for [] instead. quo keeps the exact value as a Rational, (29/4).

5min, max, minmax and max_by

min and max return the smallest and largest element, minmax returns both as a pair in one pass, and an argument asks for several: max(3) is the three largest. On an empty array they return nil. To get the larger of two values, put them in an array: [a, b].max reads better than a ternary. To keep a number inside limits, use clamp, which takes two bounds or (since Ruby 2.7) a range. To pick an element by one of its properties, use max_by, min_by or minmax_by.

min_max.rb
temps = [18, 25, 11, 31, 25, 14]

p temps.min
p temps.max
p temps.minmax

# The n smallest or largest, as a sorted array
p temps.min(2)
p temps.max(3)

# Position of the largest value
p temps.index(temps.max)

# An empty array gives nil, not an error
p [].max
p [].minmax

# The larger of two values, instead of a ternary
a = 7
b = 12
p [a, b].max

# Keep a value inside limits
p 150.clamp(0, 100)
p(-5.clamp(0, 100))
p 42.clamp(..40)

# Strings compare alphabetically; max_by picks by a value
words = %w[pear fig banana kiwi]
p words.max
p words.max_by(&:length)
p words.min_by(&:length)
p words.minmax_by(&:length)

Output

max(3) returns [31, 25, 25], largest first, and keeps the duplicate 25. index(temps.max) finds the first position of the maximum, 3. [].max is nil and [].minmax is [nil, nil], so check for an empty array before doing arithmetic with them. words.max is "pear" because strings compare alphabetically, while max_by(&:length) picks "banana", the longest. On a hash, max_by { |k, v| v } returns the winning [key, value] pair, as the next section shows.

6Totals per group: group_by, Hash.new(0) and tally

To total values per category (sales per region, hours per person), group the rows with group_by and sum each group with transform_values. The one-pass alternative is a Hash whose missing keys start at 0, Hash.new(0), which you add to as you go. When you only need how many times each value appears rather than a total, tally (Ruby 2.7 and later) counts them.

totals_per_group.rb
sales = [
  { region: "north", amount: 120 },
  { region: "south", amount: 80 },
  { region: "north", amount: 45 },
  { region: "east", amount: 200 },
  { region: "south", amount: 35 }
]

# Total per group: group_by, then sum each group
totals = sales.group_by { it[:region] }
              .transform_values { |rows| rows.sum { it[:amount] } }
p totals

# The same in one pass with a Hash that defaults to 0
totals = Hash.new(0)
sales.each { |s| totals[s[:region]] += s[:amount] }
p totals

# Count per group: tally
p sales.map { it[:region] }.tally

# The group with the largest total
p totals.max_by { |_region, total| total }

# Grand total
p totals.values.sum

Output

Both approaches print {"north" => 165, "south" => 115, "east" => 200}, with the regions in the order they first appear. tally counts two rows for north and south and one for east. max_by on the totals hash returns the pair ["east", 200], and the grand total is 480. The leading dot on .transform_values continues the chain from the line above.

7Which should you use?

MethodEmpty arrayNotesBest for
arr.sum0Compensated float sumAdding numbers: most cases
arr.sum { |e| … }0No temporary arrayA field of objects or hashes
arr.inject(:+)nil0.6000000000000001 for floatsOld code only: use sum
arr.sum.fdiv(arr.size)NaNAvoids integer divisionAn average
arr.min / max / minmaxnilmax(n) for the n largestSmallest and largest values
arr.max_by { |e| … }nilReturns the elementThe element with the largest field
group_by + sum{}Or Hash.new(0) in one passTotals per category

Frequently asked questions

Is there a sum function in Ruby like Python's sum()?

Yes, but it is a method on the collection: [1, 2, 3].sum instead of sum([1, 2, 3]). It takes an optional start value (sum(0.0), sum("")) and a block, which covers Python's sum(x.price for x in items) as items.sum(&:price). It works on arrays, ranges, hashes and any other Enumerable.

What is the difference between sum and inject(:+)?

sum returns 0 for an empty array while inject(:+) returns nil, and sum corrects float rounding ([0.1, 0.2, 0.3].sum is 0.6, inject(:+) gives 0.6000000000000001). Use sum unless you need an operation other than adding, such as inject(:*) for a product.

How do I get a running total (cumulative sum) of an array?

Keep a total outside the block and add to it in map: total = 0 then [1, 2, 3, 4].map { total += it } returns [1, 3, 6, 10]. On Ruby before 3.4, name the parameter: map { |n| total += n }.

How do I find the index of the maximum value?

arr.index(arr.max) returns the first position of the largest value. To get the value and its index together in one pass, use arr.each_with_index.max_by { |v, _i| v }, which returns [7, 1] for [3, 7, 7, 1]: the first 7 and its index.

Why does max raise "comparison of String with 1 failed"?

The array mixes types that cannot be compared, such as numbers and strings: [1, "a"].max raises ArgumentError: comparison of String with 1 failed. Convert the elements first (arr.map(&:to_i).max) or compare by a key that every element has with max_by.

How do I sum each row or each column of a 2D array?

For rows, matrix.map(&:sum); for columns, flip the matrix first: matrix.transpose.map(&:sum). With [[1, 2, 3], [4, 5, 6]] those give [6, 15] and [5, 7, 9], and matrix.sum(&:sum) or matrix.flatten.sum gives the total, 21.

How do I sum money without float errors?

Store amounts as integer cents and sum those, or use BigDecimal (require 'bigdecimal'): [BigDecimal("0.1"), BigDecimal("0.2")].sum is exactly 0.3, printed by p as 0.3e0 and by to_s("F") as 0.3. sum on floats is more accurate than + in a loop, but a Float still cannot store most decimal fractions exactly.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground