each runs the block for its side effects and returns the original array, while map collects the block's results into a new array.
Use each when something should happen for every element, such as printing or saving it. Use map when every element should become a new value.
A common mistake is to call each and expect the transformed values back. each ignores what the block returns, so the numbers.each line below still returns [1, 2, 3].
Neither method changes the original array. The bang version map! replaces the elements in place.
numbers = [1, 2, 3]
numbers.each { |n| n * 2 } # Returns [1, 2, 3]
numbers.map { |n| n * 2 } # Returns [2, 4, 6]
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓