bill bill - 1 year ago 69
Ruby Question

How to understand Ruby's .each and .map

I am having trouble understanding the differences between

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

takes each element in the array
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}

. This is confusing to me since:

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.

Answer Source

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.

Let's take an example of:

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 try doing:

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

You will get:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download