Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain a real-world, plain-language use for inject in Ruby?

Tags:

ruby

inject

I'm working on learning Ruby, and came across inject. I am on the cusp of understanding it, but when I'm the type of person who needs real world examples to learn something. The most common examples I come across are people using inject to add up the sum of a (1..10) range, which I could care less about. It's an arbitrary example.

What would I use it for in a real program? I'm learning so I can move on to Rails, but I don't have to have a web-centric example. I just need something that has a purpose I can wrap my head around.

Thanks all.

like image 702
ckbrumb Avatar asked Aug 20 '12 23:08

ckbrumb


People also ask

What is the use of inject in Ruby?

You can use the INJECT method to help you quickly sort through the elements of an array and choose the elements you want to build a new array. Here, we're asking Ruby to build us a new array of even numbers from the set we defined earlier.

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.


1 Answers

inject can sometimes be better understood by its "other" name, reduce. It's a function that operates on an Enumerable (iterating through it once) and returns a single value.

There are many interesting ways that it can be used, especially when chained with other Enumerable methods, such as map. Often times, it can be a more concise and expressive way of doing something, even if there is another way to do it.

An example like this may seem useless at first:

range.inject {|sum, x| sum += x}

The variable range, however, doesn't have to be a simple explicit range. It could be (for example) a list of values returned from your database. If you ran a database query that returned a list of prices in a shopping cart, you could use .inject to sum them all and get a total.

In the simple case, you can do this in the SQL query itself. In a more difficult case, such as where some items have tax added to them and some don't, something like inject can be more useful:

cart_total = prices.inject {|sum, x| sum += price_with_tax(x)}

This sort of thing is also particularly useful when the objects in the Enumerable are complex classes that require more detailed processing than a simple numerical value would need, or when the Enumerable contains objects of different types that need to be converted into a common type before processing. Since inject takes a block, you can make the functionality here as complex as you need it to be.

like image 171
bta Avatar answered Sep 28 '22 06:09

bta