TODAY I LEARNED

Creating an infinite loop in Ruby

If you need to iterate over a collection that its size is unknown, you can create an infinite loops in ruby easily, but if you need an index, then there's this option:

(1..).each do |page|
  results = ExternalService.get('/endpoint', page: page)
  parsed = JSON.parse(response.body)
  break if parsed['data'].empty?

  process_data(parsed['data'])
end

Tweet

Learned by Edwin Cruz on Mar 16, 2021

Discover our latest blog posts
  • #ruby
  • view raw
  • permalink
  • 1 likes
previous TIL next TIL
  • Log in
  • ?

    TIL is an open-source project by MagmaLabs that exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any MagmaLaber as well as selected friends of MagmaLabs. We hope you enjoy learning along with us.

    • /wearemagmalabs
  • statistics
  • search
  • Twitter