Ruby equivalent of C#'s 'yield' keyword, or, creating sequences without preallocating memory

后端 未结 4 2030
遥遥无期
遥遥无期 2021-01-12 05:20

In C#, you could do something like this:

public IEnumerable GetItems()
{
    for (int i=0; i<10000000; i++) {
        yield return i;
           


        
4条回答
  •  失恋的感觉
    2021-01-12 05:47

    It's supported by Enumerator since Ruby 1.9 (and back-ported to 1.8.7). See Generator: Ruby.

    Cliche example:

    fib = Enumerator.new do |y|
      y.yield i = 0
      y.yield j = 1
      while true
        k = i + j
        y.yield k
        i = j
        j = k
      end
    end
    
    100.times { puts fib.next() }
    

提交回复
热议问题