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 }
sum

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s