Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using + or += with array#map?

Tags:

arrays

ruby

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?

like image 577
MidnightKraken Avatar asked May 07 '26 06:05

MidnightKraken


1 Answers

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

like image 151
rowend Avatar answered May 09 '26 19:05

rowend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!