Reading the various explanations here on SO, they have been described as such:
Map:
The map method takes an enumerated object and a block and starts a block for each element.
Input:
Inject takes a value and a block, and it starts this block once for each list item.
I hope you understand why I feel that they seem pretty similar to the surface. When will I choose one over the other, and is there a clear difference between them?
, , inject reduce. map , . , inject ( ) .
inject
reduce
map
:
%w(a b c).map(&:upcase) #=> ["A", "B", "C"] [*1..4].inject(:+) #=> 10
, inject, fold.
inject .
arr = [] [1,2].inject(arr) { |s,e| s << e } arr # => [1,2]
. arr, #inject concatenation arr. , , arr , 1,2.
arr
#inject
concatenation
1,2
map Enumerable, - Enumerable, , Enumerable, ..
Enumerable
arr = [1,2] arr.map { |e| e + 1 } # => [2,3] arr # => [1,2]
#map 1, - , . - , arr. p arr, arr, #map.
#map
1
p arr
With injectyou usually return a single value (usually used for math), and with a map you return an array.