我是 ruby?? 新手,但我試圖解決的問題有點合乎邏輯。
我得到一個計數大約 3000 的用戶串列。但是 api 支持對 250 的回應限制,也不支持分頁或偏移。所以我必須回圈訪問這個 api,這樣每次我都會得到 250 條記錄,直到達到 3000 條記錄。并且在每一輪中,我都會為其分配一些屬性。
api 是一個獲取用戶串列的獲取請求。
api url: {{baseUrl}}/accounts/:id/users?limit=250&offset=0&count=true
api says - offset is record based, not page based,
How can I requests for users such as: First call for 0 to 250 then 250 to 500 then 500 to 750 till we reach the max count.
為了概括這一點,我認為無論我得到什么計數,它都應該遍歷所有并分配屬性。
uj5u.com熱心網友回復:
可能正在使用Range#step?
require 'uri'
require 'net/http'
(0..3000).step(250) do |offset|
uri = URI("#{base_url}/accounts/users?limit=250&offset=#{offset}")
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)
end
或者可能是無限范圍的這種方式
(0..).step(250) do |offset|
uri = URI("#{base_url}/accounts/users?limit=250&offset=#{offset}")
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
puts res.body
else
break
end
end
您也可以redo在塊中使用重復錯誤請求
uj5u.com熱心網友回復:
您可以使用Numeric#step來列舉一系列偏移量[0, 250, 500... 2750]。然后,假設get_stuff回傳一個Array,您可以使用 縫合結果Enumerator#flat_map:
stuff = 0.step(by:250, to:2999).flat_map do |offset|
get_stuff(offset, 250)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486278.html
標籤:红宝石
上一篇:替換字串中的第二個整數/數字
