How to change an array when I repeat it in Ruby?

I'm just learning Ruby, so I apologize if I'm too new here, but I can't figure it out from the pickax book (maybe just not reading it carefully enough). Anyway, if I have an array like this:

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

... and I want, for example, to multiply each value in the array by 3, I developed the following:

 arr.each {|item| item *= 3} 

... will not get me what I want (and I understand why I am not modifying the array itself).

What I am not getting is how to change the original array from within the code block after the iterator. I am sure it is very easy.

+73
arrays ruby iteration
Nov 21 '09 at 0:07
source share
3 answers

Use map to create a new array from the old:

 arr2 = arr.map {|item| item * 3} 

Use map! to change the array in place:

 arr.map! {|item| item * 3} 

See how it works on the Internet: ideone

+116
Nov 21 '09 at 0:09
source share

To directly modify an array, use arr.map! {|item| item*3} arr.map! {|item| item*3} arr.map! {|item| item*3} . To create a new array based on the original (which is often preferred), use arr.map {|item| item*3} arr.map {|item| item*3} . In fact, I always think twice before using each , because usually there is a higher order function, such as map , select or inject , that does what I want.

+15
Nov 21 '09 at 0:44
source share
 arr.collect! {|item| item * 3} 
+4
Jun 06 2018-12-12T00:
source share



All Articles