What is the purpose of the Enumerator class in Ruby

前端 未结 5 760
我在风中等你
我在风中等你 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-02 23:53

    What happens if you do enum = [1,2,3].each; enum.next?:

    enum = [1,2,3].each
    => #
    enum.next
    => 1
    enum.next
    => 2
    enum.next
    => 3
    enum.next
    StopIteration: iteration reached an end
    

    This can be useful when you have an Enumerator that does a calculation, such as a prime-number calculator, or a Fibonacci-sequence generator. It provides flexibility in how you write your code.

提交回复
热议问题