0

I am having a few problems adding to an array from within a loop. It only adds the last results to the array and loses the previous 9 sets.

I think I have to create a new array inside of the loop and then add the new one to the previous. I'm just not sure how I go about doing that.

array = Array.new

10.times do
  array2 = Array.new
  pagenum = 0
  results = Nokogiri::HTML(open("#{url}#{pagenum}"))
  results.css("div").each do |div|
    array.push div.inner_text
  end
  pagenum + 10
  array.concat(array2)
end

1 Answer 1

2

You are fetching same page (0) 10 times.

10.times do
  ...
  pagenum = 0 # <--------
  results = Nokogiri::HTML(open("#{url}#{pagenum}"))
  ...
end

Try following:

array = Array.new
10.times do |pagenum|
  results = Nokogiri::HTML(open("#{url}#{pagenum}"))
  array += results.css("div").map(&:inner_text)
end
Sign up to request clarification or add additional context in comments.

2 Comments

at the bottom of the loop I add 10 to the page number each time?
@MaxRose-Collins, pagenum + 10 does not change the value of pagenum. Maybe it's typo of pagenum += 10. Even though that typo is fixed, pagenum is reset to 0 by pagenum = 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.