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 Rubyinjectorreduce— a more general pattern for combining valueseachwith 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:
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 pilesum: ask Ruby to count the pile for youinject/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.
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:
0is the starting totaltotalkeeps the running result
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:
numbersis set to[5, 10, 20]inject(0)starts the accumulator at0- Ruby takes the first element,
5total = 0n = 5- returns
0 + 5, which is5
- Ruby takes the second element,
10total = 5n = 10- returns
5 + 10, which is15
- Ruby takes the third element,
20
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:
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:
Common Mistakes
1. Using the wrong variable name
Broken code:
Copysum = 0
array.each { |a| sum += a }
Problem:
Copysumandsumare different variablessumwas 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
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
sum | array.sum | Most numeric totals | Cleanest and most idiomatic in modern Ruby |
sum with block | `items.sum { | i | i[:price] }` |
inject / reduce | `array.inject(0) { | t, n | t + n }` |
each with variable | `sum = 0; array.each { | n | sum += n }` |
sum vs inject
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.sumfor simple numeric arrays
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:
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
- Create an array of cart items using hashes.
- Each item must include a name, price, and quantity.
- Calculate the total cost for each item as
price * quantity. - Use
sumto calculate the cart grand total. - Print each item and the final total clearly.
Keep learning
Related questions
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Difference Between require and include in Ruby
Learn the difference between require and include in Ruby, when to load a file, and when to mix module methods into a class.
Fixing Ruby Gem Native Extension Errors: mkmf.rb Can't Find Header Files for Ruby
Learn why Ruby gem installs fail with missing ruby.h, how native extensions work, and how to fix header file errors on Linux servers.