Hendrik Kleine
Hendrik Kleine

Reputation: 105

Iterate over array whilst amending the same array

The following array iteration works OK

data = [17, 22, 12, 24]
data.each do |item| 
   puts "number: #{item}"
end

I would like each new string to be inserted into the same array instead of doing puts. The following approach fails with no error. I'm not sure if this is creating an infinite loop.

data = [17, 22, 12, 24]
data.each do |item| 
    data << "number: #{item}"
 end

I also tried insert instead of <<, but the same issue comes along.

Upvotes: 1

Views: 59

Answers (2)

thaleshcv
thaleshcv

Reputation: 752

Use the Array#map! method:

data = [17, 22, 12, 24]
data.map! { |item| "number: #{item}" }

result:

["number: 17", "number: 22", "number: 12", "number: 24"]

Upvotes: 1

zwippie
zwippie

Reputation: 15515

If you want to add the new items to the array, do:

data = [17, 22, 12, 24]
data.concat data.collect{|i| "number: #{i}"}
# data => [17, 22, 12, 24, "number: 17", "number: 22", "number: 12", "number: 24"]

If you just want to replace the content of data with the new items:

data = data.collect{|i| "number: #{i}"}

Upvotes: 2

Related Questions