有什么好的方法可以在 Ruby 中模拟 yield
吗?我有兴趣在 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;
}
}
}
}
如果可以,请举例说明。
最佳答案
ruby 中实现此类序列的常用习惯是定义一个方法,如果给定一个,则为序列中的每个元素执行一个 block ,否则返回一个枚举器。看起来像这样:
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
关于c# - 您将如何在 Ruby 中简洁地编写此 C# 代码(使用 yield 关键字)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681049/