Ruby: The difference between a card and an injection

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?

+4
source share
3 answers

, , inject reduce. map , . , inject ( ) .

:

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

, inject, fold.

+8

inject .

arr = []
[1,2].inject(arr) { |s,e| s << e }
arr # => [1,2]

. arr, #inject concatenation arr. , , arr , 1,2.

map Enumerable, - Enumerable, , Enumerable, ..

arr = [1,2]
arr.map { |e| e + 1 } # => [2,3]
arr # => [1,2]

#map 1, - , . - , arr. p arr, arr, #map.

+4

With injectyou usually return a single value (usually used for math), and with a map you return an array.

+3
source

All Articles