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

前端 未结 4 964
佛祖请我去吃肉
佛祖请我去吃肉 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:13

    For example you can use it to construct Rack response bodies inline, without creating classes. An Enumerator can also work "outside-in" - you call Enumerator#each which calls next on the enumerator and returns every value in sequence. For example, you can make a Rack response body returning a sequence of numbers:

    run ->(env) {
      body = Enumerator.new do |y|
       9.times { |i| y.yield(i.to_s) }
      end
      [200, {'Content-Length' => '9'}, body]
    }
    

提交回复
热议问题