【问题标题】:How would you write this C# code (that uses the yield keyword) succinctly in Ruby?您将如何在 Ruby 中简洁地编写这段 C# 代码(使用 yield 关键字)?
【发布时间】:2011-02-10 11:35:58
【问题描述】:

有没有在 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;
            }
        }
    }
}

如果可以,请举个例子。

【问题讨论】:

  • 当一个人说“你知道现在几点了吗?”他期待的是时间,而不是“我愿意”的答案,所以你的讽刺有点毫无根据。
  • 我认为这是一个有效的问题。如果我有任何红宝石技能,我会回答它
  • 通常,我也倾向于在这个问题上回答“是”。
  • 咳嗽“乖一点”stackoverflow.com/faq

标签: c# ruby linq translation


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Fibonacci numbers with Ruby 1.9 Fibers:

    fib = Fiber.new do 
      x, y = 0, 1
      loop do 
        Fiber.yield y
        x,y = y,x+y
      end
    end
    
    20.times { puts fib.resume }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多