Understanding inject in Ruby

In Ruby, there is an enumerable called inject. It also goes by the name of reduce in Javascript. Ruby enumerable documentation (API dock), #inject is defined as such:

“Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.The #inject and #reduce methods are aliases. There is no performance benefit to either. If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element.”

So what does this mean? When should you use the #inject method in Ruby? You could use the #inject method to reduce a list into a value. . This can be used on arrays as well as hashes.

For example, if you had a shopping receipt in the format of an array. You could call #inject to add up and total out your receipts. Use# inject to create hashes and add logic to iterate through.

code from class that set me down this path

In comparison to each_with_object, #inject is better for operations on collections which return a new value. Each_with_object would be less valuable if you were attempting to modify existing objects and collections

  • #Inject combines all elements in an array/hash by passing each element into a block.
  • - The starting value is the number/hash where you want to begin
  • Accumulator is the first parameter in pipes and can optionally include a starting value by passing through an argument.
  • The iterated variable is the second parameter included in the code block.
  • The next block is the function or logic that you’re applying.

Breaking this down. This is what is going on when you start with an array:

[1, 2, 3, 4].inject(0) { |result, element| result + element }

This is what is going on when working with a hash instead of numbers.

sources: https://apidock.com/ruby/Enumerable/inject

code block from code challenge review by Ian Grubb