Search code examples
pythonrubylazy-evaluationxrange

What is Ruby's equivalent to pythons xrange?


Apparently xrange in python is faster than range. because xrange creates a sequence of objects lazily. However range creates objects in memory.

What I'd like to know is what is Ruby's equivalent of pythons xrange?


Solution

  • Ruby ranges are already lazy, like Python 3 range. Just use a range:

    1..10  # includes endpoint
    1...10 # excludes endpoint
    

    Idiomatic iteration in Ruby often doesn't involve ranges, though. For example, if you want to do a thing n times, like in your comment:

    n.times { do_something }