On 2 August 2010 05:22, jeremy Ruten <jeremy.ruten / gmail.com> wrote:
> Ruby 1.9 has the Enumerator class, which can act like a lazy list I
> think. A good example is given in the documentation:
>
> =A0fib =3D Enumerator.new { |y|
> =A0 =A0a =3D b =3D 1
> =A0 =A0loop {
> =A0 =A0 =A0y << a
> =A0 =A0 =A0a, b =3D b, a + b
> =A0 =A0}
> =A0}
>
> =A0p fib.take(10) #=3D> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>
> Also, this is a nice trick:
>
> =A0Infinity =3D 1.0/0
>
> =A0range =3D 5..Infinity
> =A0p range.take(10) #=3D> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>
> This one only works for consecutive values though.
>
> jeremy
>
> On Sun, Aug 1, 2010 at 8:56 PM, skim <skim.la / gmail.com> wrote:
>> Ruby Arrays dynamically expand as needed. =A0You can apply blocks to the=
m to
>> return things like even numbers.
>>
>> array =3D []
>> array.size # =3D> 0
>> array[0] # =3D> nil
>> array[9999] # =3D> nil
>> array << 1
>> array.size # =3D> 1
>> array << 2 << 3 << 4
>> array.size # =3D> 4
>>
>> array =3D (0..9).to_a
>> array.select do |e|
>> =A0e % 2 =3D=3D 0
>> end
>>
>> # =3D> [0,2,4,6,8]
>>
>> Does this help?
>>
>> On Sun, Aug 1, 2010 at 17:45, Andrew Wagner <wagner.andrew / gmail.com> wr=
ote:
>>
>>> How can I get a lazy array in Ruby? E.g., in Haskell, I can talk about
>>> [1..], which is an infinite list, lazily generated as needed. I can als=
o 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.
>>> Anyway, I'm sure I can do such things in Ruby, but can't seem to work o=
ut
>>> how.
>>>
>>
>

So, with Enumerator it should be:

even =3D Enumerator.new { |y|
  i =3D 0
  loop {
    y << i
    i +=3D 2
  }
}

p even.take(5) # =3D> [0, 2, 4, 6, 8]

But that is not really common practice in Ruby (Enumerator for so
simple things).

You would probably need something like (0..max).step(2) { |even_n| p even_n=
 }

B.D.