Stop what you’re doing and start using Ruby’s inject method

The Ruby inject method has a few different use cases. For me personally I’m really starting to love summing numbers with the method. It’s still a little confusing for me but I think I’m finally starting to get the hang of it.

Let’s take a look at an example.

Say we have an array of numbers that we want to sum:
[ 5, 6, 7, 8 ]

We could use a loop to sum the numbers:
sum = 0
[5,6,7,8].each { |x| sum += x }

With the inject method, we can sum the numbers on one line:
[5,6,7,8].inject(0) { |x,y| x+y }

The inject method takes an argument and a block. In this example we set the argument as “0” and the block is “|x,y| x+y”. When we call the inject method, the argument gets set as the first parameter of the block. In our case “x” would initialize to “0”. [If there is no argument then inject just takes the first element of the array as the first parameter “x”. ] Next inject takes the second parameter “y” as the first element in our array which is “5”. So now in our block we have “|0,5| 0 + 5″. This block evaluates to the integer 5 and inject stores that as “x” for the next iteration. In the next iteration we have “|5,6| 5+6″. Enumerable#inject iterates through each element of the array and sets the value of the block to the first parameter “x”. That is how it sums up all of the integers in the array.

It’s a very useful tool and can be used in a variety of instances. Using inject we save time and space by writing less code. I’ll be trying to use inject more often, especially when I have to sum certain values. I’ll get a deeper understanding of it when I use it more.


Now read this

List of sublime text shortcuts, tips and tricks

I started using sublime text over the past couple months (RIP textmate) and it’s been awesome so far. I wanted to create a short list of the shortcuts, tips and tricks that I’ve found most useful: Files cmd+p — Go to Anything cmd+ctrl+p... Continue →