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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With