-1
在Python中,我們可以寫這樣的事情,產生所有的正整數:如何在Ruby中編寫生成器?
def integer():
count = 0
while True:
count += 1
yield count
有沒有寫在Ruby中類似的發電機的方法嗎?
在Python中,我們可以寫這樣的事情,產生所有的正整數:如何在Ruby中編寫生成器?
def integer():
count = 0
while True:
count += 1
yield count
有沒有寫在Ruby中類似的發電機的方法嗎?
這是非常相似:
def integer
Enumerator.new do |y|
n = 0
loop do
y << n
n += 1
end
end
end
可以使用這樣的:
integer.take(20).inject(&:+)
# => 190
你想偷懶枚舉。在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]