Home > Software engineering >  Using or = with array#map?
Using or = with array#map?

Time:05-20

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?

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

Why would I use one over the other?

Street cred; implied Ruby badass.

{|n| n 1} is saying "I know what-the-Ruby is going on! The block returns the result of the expression. n = - don't tell me this Cargo Cult Programming crap got through code review! Stupid on display. I bet your hand calculator has an = button, you infix inbred cretins."

  • Related