我想迭代一個URL來刮。我在語法中缺少什麼?循環的語法
array = [1...100]
array.each do |i|
a = 'http://www.web.com/page/#{i}/'.scrapify(images: [:png, :gif, :jpg])
extract_images(a[:images])
end
我想迭代一個URL來刮。我在語法中缺少什麼?循環的語法
array = [1...100]
array.each do |i|
a = 'http://www.web.com/page/#{i}/'.scrapify(images: [:png, :gif, :jpg])
extract_images(a[:images])
end
array = [1...100]
沒有做什麼,你認爲它。這將創建一個具有單個元素的數組,並且該單個元素是一個Range
實例,其第一個值爲1
,最後一個值爲99
。
所以,整理出您的字符串插值問題(如注意elsewhere)之後,這樣的:
"http://www.web.com/page/#{i}/"
將是字符串:
"http://www.web.com/page/1...100/"
和遠程服務器可能不知道是什麼這意味着它將404或給你一頁;您在其他地方的評論表明,它會爲您提供第一頁,並忽略網址的...100
部分。
如果你想從1
到99
循環,那麼你會說:
(1...100).each do |i|
# `i` will range from 1 to 99 in this block
end
如果你想從循環到1
你100
會使用..
代替...
:
(1..100).each do |i|
# `i` will range from 1 to 100 in this block
end
您也可以完全消除該範圍並使用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
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
我個人喜歡['1.upto(99)'](http://ruby-doc.org/core-2.1.2/Integer.html#method-i-upto),因爲它對我來說似乎最清楚。不過,這是最好的答案,因爲它解決了OP – JKillian 2014-09-20 01:44:19
的所有問題@JKillian:我認爲'upto'可能是最好的,謝謝提醒。我很少在Ruby中做這種循環,我發現'each_with_index'或'with_index'更常見。 – 2014-09-20 02:14:13
插值你應該使用雙引號(" "
代替' '
):
array = [1...100]
array.each do |i|
a = "http://www.web.com/page/#{i}/".scrapify(images: [:png, :gif, :jpg])
extract_images(a[:images])
end
它不會找到我的網址...什麼是錯的循環 – Gibson 2014-09-20 00:52:00