What is the purpose of the Enumerator class in Ruby

前端 未结 5 736
我在风中等你
我在风中等你 2021-01-02 23:23

If I create an Enumertor like so:

enum = [1,2,3].each => # 

enum is an Enumerator. What

5条回答
  •  执笔经年
    2021-01-03 00:05

    I think, the main purpose is to get elements by demand instead of getting them all in a single loop. I mean something like this:

    e = [1, 2, 3].each
    ... do stuff ...
    first = e.next
    ... do stuff with first ...
    second = e.next
    ... do more stuff with second ...
    

    Note that those do stuff parts can be in different functions far far away from each other.

    Lazily evaluated infinite sequences (e.g. primes, Fibonacci numbers, string keys like 'a'..'z','aa'..'az','ba'..'zz','aaa'.. etc.) are a good use case for enumerators.

提交回复
热议问题