1

What is the difference between this code:

p arr = [1, 2, 3, 4, 5]
p arr.map! { |a| a + 2 }

and this code?

arr = [1, 2, 3, 4, 5]
new_arr = []

arr.each do |n|
  new_arr << n + 2
end

p arr
p new_arr

They both result in the same answer. Are they just two different ways to achieve the same solution or is there a process or application difference?

Jon
  • 93
  • 1
  • 1
  • 6
  • 3
    first approach modifies `arr` in place, whereas the second creates new array - so the second requires memory allocation, thus will be slower. Apart from this you don't have much difference – djaszczurowski Jul 12 '18 at 12:36

1 Answers1

0

The #map function "invokes the given block once for each element of self, replacing the element with the value returned by the block".

In your second example the #each method modifies each element of the array by adding + 2 and returns the modified array. The second example is based on creating a new array and filling it with modified values from the first array.

The process is pretty much the same, the main difference is that in the first example you permanently modify the array while in the second example you get to keep the first array unchanged and create a new one with modified values.

Viktor
  • 2,623
  • 3
  • 19
  • 28
  • 1
    Ah I think I see. The #map function is destructive while the #each will create a new array and preserve the original array? – Jon Jul 12 '18 at 13:37
  • 1
    The `map!` function will permanently change the array, so you could call it destructive. You can use `map` (without the exclamation mark) to gather only the result of the map function without changing the array. Your second example would be equivalent (in some way) to `new_arr = arr.map {|x| x + 2}` as you would have both the original `arr` and the `new_arr`. – Viktor Jul 12 '18 at 13:50