Himmators
Himmators

Reputation: 15016

Add items to array while looping without causing infinite loop?

I' trying to add duplicate items to an array while looping through it:

Adding it to the end causes an infitie loop:

  site.pages.each do |page|
    new_page = page.dup
    new_page.data['permalink'] = File.join('/app', page.url)
    puts new_page.data['permalink']
    puts ''
    site.pages << new_page
  end

so does adding it to the beginning.

  site.pages.each do |page|
    new_page = page.dup
    new_page.data['permalink'] = File.join('/app', page.url)
    puts new_page.data['permalink']
    puts ''
    site.pages.unshift(new_page)
  end

Upvotes: 0

Views: 57

Answers (1)

spickermann
spickermann

Reputation: 106972

I would create all the duplicates first and then add them to the array in a second step.

new_pages = site.pages.map do |page|
  new_page = page.dup
  new_page.data['permalink'] = File.join('/app', page.url)
end
site.pages += new_pages

Upvotes: 1

Related Questions