Enumerator as an infinite generator in Ruby

前端 未结 4 967
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 04:45

I\'m reading one resource explaining how Enumerators can be used as generators, which as an example like:

triangular_numbers = Enumerator.new do |yielder|
  numb         


        
4条回答
  •  攒了一身酷
    2021-02-05 05:27

    Suppose we want to print the first three triangular numbers. A naive implementation would be to use a function:

    def print_triangular_numbers steps
      number = 0
      count = 1
      steps.times do
        number += count
        count += 1
        print number, " "
      end
    end
    
    print_triangular_numbers(3)
    

    The disadvantage here is that we're mixing the printing logic with the counting logic. If we don't want to print the numbers, this isn't useful. We can improve this by instead yielding the numbers to a block:

    def triangular_numbers steps
      number = 0
      count = 1
      steps.times do
        number += count
        count += 1
        yield number
      end
    end
    
    triangular_numbers(3) { |n| print n, " " }
    

    Now suppose we want to print a few triangular numbers, do some other stuff, then continue printing them. Again, a naive solution:

    def triangular_numbers steps, start = 0
      number = 0
      count = 1
      (steps + start).times do
        number += count
        yield number if count > start
        count += 1
      end
    end
    
    triangular_numbers(4) { |n| print n, " " }
    
    # do other stuff
    
    triangular_numbers(3, 4) { |n| print n, " " }
    

    This has the disadvantage that every time we want to resume printing triangular numbers, we need to start from scratch. Inefficient! What we need is a way to remember where we left off so that we can resume later. Variables with a proc make an easy solution:

    number = 0
    count = 1
    triangular_numbers = proc do |&blk|
      number += count
      count += 1
      blk.call number
    end
    
    4.times { triangular_numbers.call { |n| print n, " " } }
    
    # do other stuff
    
    3.times { triangular_numbers.call { |n| print n, " " } }
    

    But this is one step forward and two steps back. We can easily resume, but there's no encapsulation of the logic (we could accidentally change number and ruin everything!). What we really want is an object where we can store the state. This is exactly what Enumerator is for.

    triangular_numbers = Enumerator.new do |yielder|
      number = 0
      count = 1
      loop do
        number += count
        count += 1
        yielder.yield number
      end
    end
    
    4.times { print triangular_numbers.next, " " }
    
    # do other stuff
    
    3.times { print triangular_numbers.next, " " }
    

    Since blocks are closures in Ruby, the loop remembers the state of number and count between calls. This is what makes it seem like the enumerator is running in parallel.

    Now we get to the yielder. Note that it replaces blk.call number from the previous example where we used a proc. blk.call worked, but it was inflexible. In Ruby, you don't always have to provide enumerators with blocks. Sometimes you just want to enumerate one step at a time or chain enumerators together, in those cases having your enumerator simply pass a value to a block is inconvenient. Enumerator makes enumerators much simpler to write by providing the agnostic Enumerator::Yielder interface. When you give a value to the yielder (yielder.yield number or yielder << number), you're telling the enumerator "Whenever someone asks for the next value (be it in a block, with next, each, or passed directly to another enumerator), give them this." The yield keyword simply wouldn't cut it here because it is only for yielding values to blocks.

提交回复
热议问题