In ruby 1.8.x we iterate over multiple enumerables like this:
require 'generator'
syncEnum = SyncEnumerator.new(enum1, enum2)
syncEnum.each { |x;y| puts "#{x},#{y}" }
But generator has been removed from Ruby 1.9.x, how can Iiterate over multiple enumerators in Ruby 1.9.x开发者_如何转开发?
Thanks
SyncEnumerator
seems to be moved to REXML
module:
require 'rexml/syncenumerator'
a = [1,2,3]
b = [4,5,6]
e = REXML::SyncEnumerator.new(a, b)
e.each{|i,j| p [i, j]}
#=> [1, 4]
#=> [2, 5]
#=> [3, 6]
BTW, just for practice, here's a naive implementation:
def sync_enum *enums
enums.map!(&:to_enum)
Enumerator.new do |yielder|
loop do
yielder.yield(enums.map(&:next))
end
end
end
I use the Zucker gem for this purpose. It extends Ruby with useful syntaxic sugar.
require 'zucker/control'
a = [1,2,3]
b = [4,5,6]
iterate(a, b) { |i,j| p [i, j] }
#=> [1, 4]
#=> [2, 5]
#=> [3, 6]
精彩评论