Search code examples
rubylazy-evaluation

How can I get a lazy array in Ruby?


How can I get a lazy array in Ruby?

In Haskell, I can talk about [1..], which is an infinite list, lazily generated as needed. I can also do things like iterate (+2) 0, which applies whatever function I give it to generate a lazy list. In this case, it would give me all even numbers.

I'm sure I can do such things in Ruby, but can't seem to work out how.


Solution

  • With Ruby 1.9 you can use the Enumerator class. This is an example from the docs:

      fib = Enumerator.new { |y|
        a = b = 1
        loop {
          y << a
          a, b = b, a + b
        }
      }
    
      p fib.take(10) #=> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    

    Also, this is a nice trick:

      Infinity = 1.0/0
    
      range = 5..Infinity
      p range.take(10) #=> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    

    This one only works for consecutive values though.