2016-09-07 164 views
-1

在Python中,我们可以写这样的事情,产生所有的正整数:如何在Ruby中编写生成器?

def integer(): 
    count = 0 
    while True: 
    count += 1 
    yield count 

有没有写在Ruby中类似的发电机的方法吗?

回答

2

这是非常相似:

def integer 
    Enumerator.new do |y| 
    n = 0 
    loop do 
     y << n 
     n += 1 
    end 
    end 
end 

可以使用这样的:

integer.take(20).inject(&:+) 
# => 190 
0

你想偷懒枚举。在Ruby 2.3.1中(至少早在Ruby 2.2.0中),你可以通过在Enumerator::Lazy中混合来创建一个。然而,如果你想要的只是一个无限的整数流,你可以使用一个Range对象。例如:

(1 .. Float::INFINITY).take 10 
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]