- Read Tutorial
- Watch Guide Video
In this lesson I'm going to examine how to sum up values in Ruby by implementing the
inject method. Being able to sum up values in an array is something you will most likely need in a number of different situations. Thankfully Ruby makes this very straightforward to implement.
Before we see how to implement the
inject method, I think it's beneficial to review how to generate a sum manually:
total = 0 [3, 2, 4, 53, 5, 3, 23343, 4342, 12, 3].each do |i| total += i end puts total
When you run this program it will generate the value
27700, which is the sum of all the individual values present in the array.
However, that took four lines of code. To shorten it we can use the
[3, 2, 4, 53, 5, 3, 23343, 4342, 12, 3].inject(&:+)
In this code we are calling the
inject method and passing it to each element in the array. The
inject method is similar to
select in the way that it looks at each element in a collection. However it differs in the sense that it keeps track of the variable value with each iteration. This makes it possible to easily increment all of values in a collection and is thus perfect for creating sums.
inject is not limited to creating sums. If we want to multiply all of the values in a collection we can replace
[3, 2, 4, 53, 5, 3, 23343, 4342, 12, 3].inject(&:*)
So how exactly was it this easy? It's because
+ is not an operator in Ruby, rather it is a method. In other programming languages, the parser interprets these symbols as operators, but Ruby treats it as a method and sends it to each of the values of the collection its iterating through.
So, this is how easy it is to generate a sum from values in an array in Ruby.