When is the Enumerator::Yielder#yield method useful?

前端 未结 4 957
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 12:03

The question \"Meaning of the word yield\" mentions the Enumerator::Yielder#yield method. I haven\'t used it before, and wonder under what circumstances it would be

4条回答
  •  醉话见心
    2021-02-13 12:25

    Since Mladen mentioned getting other answers, I thought I would give an example of something I just did earlier today while writing an application that will receive data from multiple physical devices, analyze the data, and connect related data (that we see from multiple devices). This is a long-running application, and if I never threw away data (say, at least a day old with no updates), then it would grow infinitely large.

    In the past, I would have done something like this:

    delete_old_stuff if rand(300) == 0
    

    and accomplish this using random numbers. However, this is not purely deterministic. I know that it will run approximately once every 300 evaluations (i.e. seconds), but it won't be exactly once every 300 times.

    What I wrote up earlier looks like this:

    counter = Enumerator.new do |y|
      a = (0..300)
      loop do
        a.each do |b|
          y.yield b
        end
        delete_old_stuff
      end
    end
    

    and I can replace delete_old_stuff if rand(300) == 0 with counter.next

    Now, I'm sure there is a more efficient or pre-made way of doing this, but being sparked to play with Enumerator::Yielder#yield by your question and the linked question, this is what I came up with.

提交回复
热议问题