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 "Ruby Iterators" but wanted some clarification.
If I have:
z = [1,2,3].map {|x| x + 1}
map
takes each element in the array z
and adds one to each element, however it does not mutate the original array unless I add !
.
On the other hand:
y = [1,2,3].each {|x| x + 1}
returns [1,2,3]
. This is confusing to me since:
names = ['danil', 'edmund']
names.each { |name| puts name + ' is a programmer' }
returns:
Danil is a programmer
Edmund is a programmer
What is exactly going on in my second example that isn't allowing each array element to be increased by 1
, while in the last example a string is being attached to everything in the array?
All credits go to Speransky Danil, whom I took these examples off of.