Reputation: 21
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map {|n| n + 1}
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map {|n| n += 1}
These both return [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
but i'm not understanding whats the difference in using +
or +=
in a map array. Why would I use one over the other?
Upvotes: 2
Views: 110
Reputation: 432
The Array#map function iterates over Array and executes the block once for each element in it's own scope. Each time the n += 1 executes, Array#map first sets the value of n to to the element being mapped. It is not held over or accumulated for subsequent iterations.
If you wanted to accumulate on purpose, you have to add something to a variable outside the block.
irb(main):001:0> a = 0
=> 0
irb(main):002:0> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map {|n| a += n }
=> [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
irb(main):003:0> a
=> 55
Upvotes: 2
Reputation: 29766
There is no difference, because only the return value inside map
block matters. You can do what you like with n
but if you return something else, that's what counts:
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map {|n| n += 1; 1} # return 1 for everything
=> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
For example, n += 1
and n + 1
both return 2
if n is 1, so there is no difference.
It is however significant inside the map
block:
>> [1].map {|n| n + 10; n} # `+` does not change `n`
=> [1]
>> [1].map {|n| n += 10; n} # `+=` does change `n`
=> [11]
Upvotes: 2
Reputation: 168
In ruby in most cases the last expression is returned.
Inside the block (in both cases) you have only one expression and this will be the result per item.
One expression is n + 1
and this will be 1 + 1
, 2 + 1
, 3 + 1
, etc
The other expression is n += 1
and this will be n = n + 1
so n = 1 + 1
, n = 2 + 1
, n = 3 + 1
The same result, but in the second you make an extra assignment
The first expression n + 1
is in some way is more efficient because you do not assign the value again to n
The second expression n +=1
could be useful if you need to make other operations with n
inside of the block
Upvotes: 6