bill bill - 1 month ago 7x
Ruby Question

Understanding .each and .map (Ruby)

I am currently reading my ruby book and am having trouble understanding some slight differences and where and when to use them.

I have read What does map do? and have learned alot but I wanted some clarification. I have also read Ruby Iterators

For starts, I would like to consider

z = [1,2,3].map {|x| x + 1}

Here map takes each element in the array
and adds one to each element, however it does not mutate the original array unless we add

On the other hand consider

y = [1,2,3].each {|x| x + 1}

This returns
.. this is a bit confusing to me since the following

names = ['danil', 'edmund']
names.each { |name| puts name + ' is a programmer' }


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
, 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.



The map method takes an enum given some block, and iterates through it doing some logic. In your case the logic is x+1. As you say it will not mutate anything unless you use !

each is simply returning the array that is being called!

Lets take your example

Say names = ["bob"]

If we do names.each{|names| names + "somestring"}

The output is still ["bob"]! The reason your second example is different is due to the puts.

As an exercise why dont you try doing y = [1,2,3].each {|x| puts x + 1} You will get