Difference Between map and each
each
returns the original object. It's used to run an operation using each element of an array without collecting any of the results. For example, if you want to print a list of numbers, you might do something like this:
arr = [1, 2, 3, 4]
arr.each { |n| puts n }
Now, that puts
method above actually returns nil
. Some people don't know that, but it doesn't matter much anyway; there's no real reason to collect that value (if you wanted to convert arr
to strings, you should be using arr.map(&:to_s)
or arr.map { |n| n.to_s }
.
map
returns the results of the block you pass to it. It's a great way to run an operation on each element in an array and retrieve the results. If you wanted to multiple every element of an array by 2, this is the natural choice. As a bonus, you can modify the original object using map!
. For example:
arr = [1, 2, 3, 4]
arr.map! { |n| n * 2}
# => [2, 4, 6, 8]
each
simply iterates over the given enumerable, running the block for each value. It discards the return value of the block, and each simply returns the original object it was called on:
[1, 2, 3].each do |x|
x + 1
end # => [1, 2, 3]
This is simply a nicer, more universal way of doing a traditional iterating for
loop, and each
is much preferred over for
loops in Ruby (in fact, I don't think I've ever used a for
loop in Ruby).
map
, however, iterates over each element, using the return value of the block to populate a new array at each respective index and return that new array:
[1, 2, 3].map do |x|
x + 1
end # => [2, 3, 4]
So it “maps” each element to a new one using the block given, hence the name “map”. Note that neither each
nor map
themselves modify the original collection. This is a concise, functional alternative to creating an array and pushing to it in an iterative loop.