Question

How to Sum an Array of Numbers in Ruby

rubyarraysmathsum

Question

I have an array of integers, for example:

array = [123, 321, 12_389]

What is a clean and idiomatic way to calculate the total sum of all values in the array?

I know this approach would work:

sum = 0
array.each { |a| sum += a }

But is there a nicer Ruby way to do it?

Short Answer

By the end of this page, you will understand how to add all numbers in a Ruby array using the most common and idiomatic approaches. You will learn when to use sum, how inject/reduce works, how manual accumulation with each compares, and what mistakes beginners often make.

Concept

In Ruby, summing an array means combining all its elements into one total value. This is a very common operation in programming because collections of numbers appear everywhere: prices, scores, quantities, durations, and statistics.

Ruby provides several ways to do this:

  • sum — the simplest and most readable option in modern Ruby
  • inject or reduce — a more general pattern for combining values
  • each with a running total — a manual approach that shows what is happening internally

The key idea is accumulation: start with an initial value, then visit each item and add it to the total.

For example, given:

[2, 4, 6]

The sum is calculated like this:

  • start at 0
  • add 2 → 2
  • add 4 → 6
  • add 6 → 12

This matters because many real tasks are just variations of accumulation:

  • total order price
  • total API response time
  • total points in a game
  • total file sizes
  • total hours worked

Once you understand summing, you are also very close to understanding more general collection operations like counting, finding averages, and reducing data into a single result.

Mental Model

Think of an array like a row of coins on a table.

You want to know how much money you have in total.

There are three ways to do it:

  • each: pick up each coin one by one and add it to a running pile
  • sum: ask Ruby to count the pile for you
  • inject/reduce: use a folding process where one total is carried forward through every item

The important mental image is this:

  • the array contains many values
  • summing turns those many values into one final value

So sum is like pressing a calculator button that totals the whole list.

Take Quiz

Syntax and Examples

Using sum

In modern Ruby, the cleanest way is:

array = [123, 321, 12_389]
puts array.sum

Output:

12833

This is usually the best choice because it is short, readable, and clearly expresses your intent.

Using inject or reduce

Before sum became common, Ruby developers often used inject:

array = [123, 321, 12_389]
puts array.inject(0) { |total, n| total + n }

Output:

12833

Explanation:

  • 0 is the starting total
  • total keeps the running result
  • n is the current number from the array
  • each step returns a new total

reduce is an alias for inject, so this does the same thing:

array = [123, 321, 12_389]
puts array.reduce(0) { |total, n| total + n }

Using each manually

array = [123, 321, 12_389]
sum = 0

array.each do |n|
  sum += n
end

puts sum

This works well and is useful for learning, but it is more verbose than sum.

Summing with a block

You can also sum computed values:

products = [
  { price: 10, quantity: 2 },
  { price: 5, quantity: 4 }
]

total = products.sum { |p| p[:price] * p[:quantity] }
puts total

Output:

40

This is helpful when you do not want to sum the original items directly, but rather a value derived from each item.

Step by Step Execution

Consider this example:

numbers = [5, 10, 20]
result = numbers.inject(0) { |total, n| total + n }
puts result

Here is what happens step by step:

  1. numbers is set to [5, 10, 20]
  2. inject(0) starts the accumulator at 0
  3. Ruby takes the first element, 5
    • total = 0
    • n = 5
    • returns 0 + 5, which is 5
  4. Ruby takes the second element, 10
    • total = 5
    • n = 10
    • returns 5 + 10, which is 15
  5. Ruby takes the third element, 20
    • total = 15
    • n = 20
    • returns 15 + 20, which is 35
  6. inject finishes and returns 35
  7. puts result prints 35

You can think of the running total like this:

StepCurrent numberRunning total
Start—0
155
21015
32035

The same underlying idea applies to sum, but Ruby hides the loop for you.

Real World Use Cases

Summing arrays is used in many everyday programming tasks.

E-commerce totals

prices = [19.99, 5.50, 12.00]
total = prices.sum

Used for:

  • shopping carts
  • invoice totals
  • checkout calculations

Analytics and reporting

daily_signups = [12, 18, 21, 9, 15]
weekly_total = daily_signups.sum

Used for:

  • total visits
  • total downloads
  • total registrations

Time tracking

hours = [2.5, 3.0, 1.5, 4.0]
total_hours = hours.sum

Used for:

  • freelance billing
  • employee timesheets
  • project reporting

Scores and game logic

scores = [100, 250, 75]
final_score = scores.sum

Used for:

  • total player score
  • round-based results
  • leaderboard calculations

Summing derived values

orders = [
  { subtotal: 20, tax: 2 },
  { subtotal: 15, tax: 1.5 }
]

grand_total = orders.sum { |o| o[:subtotal] + o[:tax] }

Used when values need calculation before being added.

Take Quiz

Real Codebase Usage

In real Ruby projects, developers usually prefer the most expressive option for the job.

Common pattern: use sum for readability

total_price = items.sum { |item| item.price_cents }

This is common in Rails apps, scripts, and service objects because it clearly says: “sum these values.”

Validation before summing

If data may be missing or invalid, code often filters first:

values = [10, nil, 20, nil, 5]
total = values.compact.sum

This avoids errors from nil values.

Guard clauses

Developers often return early if there is nothing to sum:

def total_score(scores)
  return 0 if scores.empty?

  scores.sum
end

This makes intent obvious and handles edge cases cleanly.

Combining with map

A common pattern is to extract values, then sum them:

orders = [
  { total: 100 },
  { total: 250 },
  { total: 75 }
]

grand_total = orders.map { |o| o[:total] }.sum

Or more compactly:

grand_total = orders.sum { |o| o[:total] }

Error-resistant data handling

In production code, arrays are not always perfectly clean. Developers often normalize data first:

inputs = ["10", "20", "30"]
total = inputs.map(&:to_i).sum

This is useful when values come from forms, CSV files, or APIs.

Common Mistakes

1. Using the wrong variable name

Broken code:

Copysum = 0
array.each { |a| sum += a }

Problem:

  • Copysum and sum are different variables
  • sum was never initialized

Correct version:

sum = 0
array.each { |a| sum += a }

2. Using a constant by mistake

In Ruby, names starting with a capital letter are treated as constants.

Broken style:

Sum = 0

Use a local variable instead:

sum = 0

3. Forgetting that arrays may contain non-numeric values

Broken code:

values = [10, "20", 30]
puts values.sum

This can fail because Ruby cannot automatically add integers and strings.

Fix it by converting values first:

values = [10, "20", 30]
puts values.map(&:to_i).sum

4. Not handling nil

Broken code:

values = [10, nil, 20]
puts values.sum

Fix:

values = [10, nil, 20]
puts values.compact.sum

5. Overusing each when sum is clearer

This works:

sum = 0
array.each { |n| sum += n }

But this is usually better:

array.sum

Prefer the version that communicates intent most directly.

6. Forgetting the initial value in inject

This often works for numeric arrays:

array.inject { |total, n| total + n }

But using an explicit starting value is clearer and safer:

array.inject(0) { |total, n| total + n }

This is especially important when the array might be empty.

Comparisons

ApproachExampleBest forNotes
sumarray.sumMost numeric totalsCleanest and most idiomatic in modern Ruby
sum with block`items.sum {ii[:price] }`
inject / reduce`array.inject(0) {t, nt + n }`
each with variable`sum = 0; array.each {nsum += n }`

sum vs inject

  • Use sum when your goal is specifically adding values
  • Use inject when you want a more general “combine everything into one result” pattern

Example of inject doing more than sum:

words = ["Ruby", "is", "fun"]
sentence = words.inject("") { |result, word| result + word + " " }
puts sentence.strip

sum is specialized. inject is general.

each vs sum

  • each gives manual control
  • sum gives cleaner intent

If your only goal is getting a total, sum is usually the better choice.

Take Quiz

Cheat Sheet

Quick reference

Sum an array of numbers

array = [1, 2, 3]
array.sum
# => 6

Sum with a block

items.sum { |item| item[:price] }

Sum manually with each

sum = 0
array.each { |n| sum += n }

Sum with inject

array.inject(0) { |total, n| total + n }

Remove nil values first

array.compact.sum

Convert strings to integers first

array.map(&:to_i).sum

Rules of thumb

  • Prefer array.sum for simple numeric arrays
  • Use sum { ... } when each item needs calculation
  • Use inject(0) when learning or doing a custom reduction
  • Initialize manual totals with 0
  • Use lowercase variable names like sum, not Sum

Edge cases

  • Empty array with sum returns 0
  • Arrays containing nil should usually use compact
  • Arrays containing strings may need map(&:to_i) or map(&:to_f)

FAQ

How do you sum an array in Ruby?

Use sum:

[1, 2, 3].sum
# => 6

What is the idiomatic Ruby way to add all array values?

In modern Ruby, array.sum is usually the most idiomatic and readable choice.

Can I use inject instead of sum in Ruby?

Yes. For example:

array.inject(0) { |total, n| total + n }

It works well, but sum is simpler when you only need addition.

What happens if the array is empty?

[].sum
# => 0

This is one reason sum is convenient.

How do I sum an array that contains nil values?

Remove nil values first:

[1, nil, 3].compact.sum
# => 4

How do I sum numeric strings in Ruby?

Convert them first:

["10", "20", "30"].map(&:to_i).sum
# => 60

Is reduce different from inject in Ruby?

No. reduce is an alias for inject. They do the same thing.

Should I use each to sum values in Ruby?

You can, but sum is usually shorter and clearer unless you specifically want to show the manual process.

Take Quiz

Mini Project

Description

Build a small Ruby script that calculates the total cost of items in a shopping cart. This demonstrates how summing arrays is used in real applications, especially when each item has a price and quantity. You will practice both basic summing and summing computed values from structured data.

Goal

Create a Ruby program that calculates the grand total of a shopping cart using sum.

Requirements

  1. Create an array of cart items using hashes.
  2. Each item must include a name, price, and quantity.
  3. Calculate the total cost for each item as price * quantity.
  4. Use sum to calculate the cart grand total.
  5. Print each item and the final total clearly.
Take Quiz

Keep learning

Related questions

View more