Search code examples
arraysloopscrystal-lang

How to properly modify an array while iterating it


In Crystal, I want to change the Array I'm iterating over I do this:

strings = ["A","B","C"]

i = 0
strings.each do |string|
  strings[i] = string * 2
  i += 1
end

While it isn't the worst thing, I feel like there should be a more idiomatic way to achieve it, something like:

strings = ["A","B","C"]

strings.each do |string|
  string = string * 2
end

Is there anything like this possible in Chrystal? Preferably something removing the need for an additional variable such as i in this case. If so, is it considered a good practice?


Solution

  • You're probably looking for Array#map!

    In this case strings.map! {|string| string*2} does exactly the same.