开发者

syncEnumerator equivalent in ruby 1.9.2

开发者 https://www.devze.com 2023-02-22 05:45 出处:网络
In ruby 1.8.x we iterate over multiple enumerables like this: require \'generator\' syncEnum = SyncEnumerator.new(enum1, enum2)

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号