如何制作一个通过其他两个枚举器进行惰性迭代的ruby枚举器? [英] How can I make a ruby enumerator that does lazy iteration through two other enumerators?
问题描述
假设我有两个枚举器enum1
和enum2
,它们必须延迟进行迭代(因为它们有副作用).我该如何构造第三个枚举器enum3
,其中enum3.each{|x| x}
会 lazily 返回enum1 + enum2
的等价物?
Let's say I have two enumerators, enum1
and enum2
that must be lazily iterated through (because they have side effects). How do I construct a third enumerator enum3
where enum3.each{|x| x}
would lazily return the equivalent of enum1 + enum2
?
在我的实际用例中,我正在流式传输两个文件,并且需要流式传输串联.
In my real world use case, I'm streaming in two files, and need to stream out the concatenation.
推荐答案
这似乎正是我想要的;
This seems to work just how I want;
enums.lazy.flat_map{|enum| enum.lazy }
这是示范.定义这些产生副作用的方法;
Here's the demonstration. Define these yielding methods with side-effects;
def test_enum
return enum_for __method__ unless block_given?
puts 'hi'
yield 1
puts 'hi again'
yield 2
end
def test_enum2
return enum_for __method__ unless block_given?
puts :a
yield :a
puts :b
yield :b
end
concated_enum = [test_enum, test_enum2].lazy.flat_map{|en| en.lazy }
然后在结果上调用,表明副作用是懒惰发生的;
Then call next on the result, showing that the side effects happen lazily;
[5] pry(main)> concated_enum.next
hi
=> 1
[6] pry(main)> concated_enum.next
hi again
=> 2
这篇关于如何制作一个通过其他两个枚举器进行惰性迭代的ruby枚举器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!