Gibson
Gibson

Reputation: 2085

Syntax of loops

I'm trying to iterate a URL to scrape. What am I missing in my syntax?

array = [1...100]

array.each do |i|
    a = 'http://www.web.com/page/#{i}/'.scrapify(images: [:png, :gif, :jpg])
    extract_images(a[:images])
end

Upvotes: 0

Views: 64

Answers (2)

mu is too short
mu is too short

Reputation: 434955

array = [1...100] doesn't do what you think it does. That creates an array with a single element and that single element is a Range instance whose first value is 1 and whose last value is 99.

So, after sorting out your string interpolation problem (as noted elsewhere), this:

"http://www.web.com/page/#{i}/"

will be the string:

"http://www.web.com/page/1...100/"

and the remote server probably doesn't know what that means and it will either 404 or give you page one; your comments elsewhere suggest that it will give you page one and ignore the ...100 part of the URL.

If you want it loop from 1 to 99 then you'd say:

(1...100).each do |i|
  # `i` will range from 1 to 99 in this block
end

If you want to loop from 1 to 100 you'd use .. instead of ...:

(1..100).each do |i|
  # `i` will range from 1 to 100 in this block
end

You could also ditch the range completely and use times:

99.times do |i|
  # `i` will range from 0 to 98 in this block so
  # you'd work with `i+1`
end

100.times do |i|
  # `i` will range from 0 to 99 in this block so
  # you'd work with `i+1`
end

or upto (thanks to JKillian for the reminder about this one):

1.upto(99) do |i|
  # `i` will range from 1 to 99 in this block
end

1.upto(100) |i|
  # `i` will range from 1 to 100 in this block
end

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

For interpolation you should use double quotes(" " instead ' '):

array = [1...100]

array.each do |i|
    a = "http://www.web.com/page/#{i}/".scrapify(images: [:png, :gif, :jpg])
    extract_images(a[:images])
end

Upvotes: 2

Related Questions