How To Inject In Ruby

In this post, we will be discussing one of Ruby’s most versatile and powerful methods: the inject method, also known as reduce. Inject is an enumerable method commonly used to accumulate values from a collection, such as an array or a hash. It can be used to perform operations like summation, multiplication, or even building hashes.

Let’s dive into some examples to understand how the inject method works in Ruby and how it can be utilized in various situations!

Basic Usage of Inject

The inject method takes an initial value and a block of code as arguments. The block will be executed for each element in the collection. The result of the block execution will be stored and used as the initial value for the next iteration. The final result will be returned after the last iteration. Here’s the basic syntax of the inject method:

collection.inject(initial_value) { |accumulator, element| … }

Let’s start by using inject to calculate the sum of elements in an array:

array = [1, 2, 3, 4, 5]
sum = array.inject(0) { |accumulator, element| accumulator + element }
puts sum # Output: 15

In the example above, we pass 0 as the initial value for the accumulator. The block of code will then add each element of the array to the accumulator, resulting in the sum of all elements.

Inject with Symbol as Argument

For simple operations like addition, subtraction, multiplication, and division, you can also pass the operator symbol as an argument to the inject method, like this:

array = [1, 2, 3, 4, 5]
sum = array.inject(:+)
puts sum # Output: 15

In this case, inject will use the + symbol to perform the sum operation for each element in the array.

Building Hashes with Inject

Inject can also be used to build hashes from arrays. Let’s assume we have an array of arrays and want to convert it into a hash. Here’s how we can do it using inject:

array = [[‘apple’, 3], [‘banana’, 5], [‘orange’, 2]]
hash = array.inject({}) { |accumulator, element| accumulator[element[0]] = element[1]; accumulator }
puts hash.inspect
# Output: {“apple”=>3, “banana”=>5, “orange”=>2}

In this example, the initial value of the accumulator is an empty hash {}. The block of code assigns the first element of each inner array as a key and the second element as a value in the hash. The final result is a hash with the desired key-value pairs.

Conclusion

The inject method in Ruby is a powerful and flexible tool for accumulating values and performing operations on collections. In this post, we have explored some basic usage of inject, as well as a more advanced example with hash building. However, there are many more possibilities with inject, and exploring them will enhance your Ruby programming skills. Happy coding!