c# - 您将如何在 Ruby 中简洁地编写此 C# 代码(使用 yield 关键字)?

标签 c# ruby linq translation

有什么好的方法可以在 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/

相关文章:

c# - Access DB - 操作必须使用可更新查询

.net - EF 在 linq 查询中比较格式 "YYYYMMDD"的日期字符串?

c# - 非静态字段、方法或属性需要对象引用

c# - 如何在 C# 应用程序中访问这种类型的 C++ 共享内存?

c# - 如何并行化 IEnumerable 的 IEnumerable?

python - 修改MongoDB中所有文档的字段时间格式的有效方法

ruby - 运行一个进程,捕获其输出并退出代码

C# 使用 MySQL 连接数据库

c# - API C# - 如何获取另一个程序中插入符号所在的文本框的句柄?

ruby-on-rails - 如何使 update_attributes 因批量分配警告而失败