你会如何在Ruby中简洁地编写这个C#代码(使用yield关键字)?

Val*_*yev 1 c# ruby linq translation

有没有一种yield在Ruby中模拟的好方法?我有兴趣在Ruby中编写类似的"无限fib序列".

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;


namespace cs2 {
    class Program {
        static void Main(string[] args) {          
          var i=Fibs().TakeWhile(x=>x < 1000).Where(x=>x % 2==0).Sum();
        }

        static IEnumerable<long> Fibs() {
            long a = 0, b = 1;
            while (true) {
                yield return b;
                b += a;
                a = b - a;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有可能,请举个例子.

sep*_*p2k 10

ruby中用于实现此类序列的常用习惯用法是定义一个方法,如果给出一个元素,则为序列中的每个元素执行一个块,如果不是,则返回一个枚举器.这看起来像这样:

def fibs
  return enum_for(:fibs) unless block_given?
  a = 0
  b = 1
  while true
    yield b
    b += a
    a = b - a
  end
end

fibs
#=> #<Enumerable::Enumerator:0x7f030eb37988>
fibs.first(20)
#=> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
fibs.take_while {|x| x < 1000}.select {|x| x%2 == 0}
#=> [2, 8, 34, 144, 610]
fibs.take_while {|x| x < 1000}.select {|x| x%2 == 0}.inject(:+)
=> 798
Run Code Online (Sandbox Code Playgroud)