How do I modify an array while I am iterating over it in Ruby?
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.