How do I modify an array while I am iterating over it in Ruby? How do I modify an array while I am iterating over it in Ruby? arrays arrays

How do I modify an array while I am iterating over it in Ruby?


Use map to create a new array from the old one:

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

Use map! to modify the array in place:

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

See it working online: ideone


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


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