Galiwango Ananiya
3 min readJul 6, 2021

Leverage the power of ruby inject method to build a collection

When it comes to implementing mathematical solutions a very common pattern that you are going to see is being asked to implement a Fibonacci sequence. In this article, we are going to write a ruby method to generate a Fibonacci sequence using the inject enumerable method.

If you are not familiar with the Fibonacci sequence, it is one that is formed by Fibonacci numbers such that each number is the sum of the two preceding ones, starting from 0 and 1. For a detailed explanation of Fibonacci numbers check out this Wikipedia article Fibonacci number.

So, this is a very common kind of pattern, but it can be a little bit tricky if you have never had to implement it before, and one of the tricks is using the inject method, not once but actually using it twice and starting off a default value, and that’s what we are going to implement here.

We are going to create a method called fibonacci and it takes a number because we want the ability to generate any number of Fibonacci sequence numbers.

So, as you may have guessed we are going to start off with a range, starting from 1 to whatever number gets passed in so in other words when we want the first 10 items, this is going to go from 1 to 10.

Now the next thing we need to do is pass in the inject method but instead of just starting off inject at 0, we are going to do something a little bit different here, we are going to start it off with an array of 0 and 1, so this is going to give us a starting point for the Fibonacci value, and these first two values are 0 and 1.

That is the first part, now what we need to do is to have a nested inject method, but remember that inside of our inject we have our accumulator and here we are just going to call it fib, and what we want to do with fib is add it and this is going to be an array, and the reason we know it’s going to be an array is because we are starting with 0 and 1 as our default value which also doubles as our accumulator and instead of starting with a number like how we would usually do for just summing values, we are starting with an array and this fib block variable is going to represent this array.

Next, we are going to get the last two elements using fib.last(2), call the inject method again on these two elements to sum them up, and finally append them to fib.

That one line of code should suffice. If we run this code, it gives us the exact Fibonacci sequence based on the number you pass into the method, hopefully, you can see how intuitive it is by leveraging inject and nesting that inside of another inject.