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

后端 未结 4 2071
遥遥无期
遥遥无期 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:48

    Without having much ruby experience, what C# does in yield return is usually known as lazy evaluation or lazy execution: providing answers only as they are needed. It's not about allocating memory, it's about deferring computation until actually needed, expressed in a way similar to simple linear execution (rather than the underlying iterator-with-state-saving).

    A quick google turned up a ruby library in beta. See if it's what you want.

提交回复
热议问题