I am having trouble understanding the differences between map
and each
, and where and when to use them.
I read \"What does map do?\" and \
tl;dr: I use map
if I want to change my collection, apply a transformation on it, end up with something different. I use each
if I just need to visit every element in a collection.
Key point is: you should use map
if you want to apply a transformation on an array (an enumerable in reality, but let's keep it simple at the beginning). Otherwise, if you don't need to change your array, you can simply use each
.
Note that in the code below you are not mutating the array but you are simply take advantage of the local string to print each string with a suffix.
names = ['danil', 'edmund']
names.each { |name| puts name + ' is a programmer' }
Obviously, you could do the same with map
but in this case you don't need it and you have to use an each too to print every element. The code would be
names = ['danil', 'edmund']
names.map! { |name| name + ' is a programmer' }
# or names = names.map { |name| name + ' is a programmer' }
name.each { |name| puts name }