What is array.inject() in Ruby?
The inject method in Ruby
The inject method in Ruby is defined in enum.c, also known as enumerable. Enumerable is a collection of classes such as arrays, hashes, and structs that includes search and traversal methods.
The inject method sequentially accesses the elements of the enumerator and operates on them. It is most commonly used for arrays and behaves similarly to Ruby's reduce method.
The syntax for inject is given below:
## Defining initial operand and symbolinject(initial, sym) ⇒ Object## Defining initial value before the memo, obj, and operationinject(initial) {|memo, obj| ... } ⇒ Object## Calling inject method without specifying initial valueinject {|memo, obj| ... } ⇒ Object
Line 2: We only define the
initialoperand and thesymbol. This means that we can assign aninitialvalue on which we wish to start applying the operation indicated by the symbol.Line 5: We define the
initialvalue before and then thememo,objand the operation to be applied which is denoted by.... Theobjaccesses each value of the enumerator, applies the operation, and stores the final value inmemo.Line 8: We do not specify an initial value while calling the
injectmethod.
Parameters
The array.inject method takes the mapping function as input to apply it to the elements of an array. Along with the operator that will be applied to the array. We also specify an accumulator value memo and an element obj. The obj collects each element of the array and memo stores the value after the operation has been applied
Return value
The array.inject method returns a value corresponding to the mapping function performed on the array.
Example
The following example will help explain how one can use the array.inject method.
num = [1,2,3,4,5]## Calling inject function with subtract operatorputs num.inject(:-)## Calling inject function with modified operatorputs num.inject{|difference, n| difference-n}
In the code above, we started by defining an array called num. After this, we call the inject function using the - operator. This means that the function will take each element of the array and subtract it from the next. In this case, it performs (((1-2)-3)-4)-5 which results in -13.
We can redefine this function by taking each number n and subtracting it from the difference. The variable difference saves the result of each subtraction to facilitate the subtraction from the next element of the array.
Setting the initial operand
The syntax indicates that the inject method can be called in different ways. The main difference lies in setting the initial operand.
num = [1,2,3,4,5]## Calling inject method with the operand and operatorputs num.inject(0, :-)## Setting initial operator before defining memo, obj, and operatorputs num.inject(0){|difference, n| difference-n}
As shown in the code above:
Line 4: We set the
initialoperand with the symbol.Line 7: We set the
initialoperand before defining thememo,obj,and operator.
Free Resources