Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Difference between map and inject

Tags:

ruby

Reading various explanations here on SO, they have been described as such:


Map:

The map method takes an enumerable object and a block, and runs the block for each element


Inject:

Inject takes a value and a block, and it runs that block once for each element of the list.

Hopefully you understand why I feel they seem pretty similar on the surface. When would I pick one over the other, and is there any clear-cut difference between them?

like image 395
krystah Avatar asked Jan 21 '14 14:01

krystah


1 Answers

It helps if you consider that inject is also aliased as reduce. map is used to transform a list, e.g. convert all strings in the array to uppercase, whereas inject takes an argument (usually an accumulator) and modifies that.

Examples:

 %w(a b c).map(&:upcase) #=> ["A", "B", "C"]
 [*1..4].inject(:+) #=> 10

If you want to read more, what inject does is referred to as a fold.

like image 105
Michael Kohl Avatar answered Oct 04 '22 03:10

Michael Kohl