This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Iterating over multiple arrays
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
The ability to iterate over multiple collections at once is an often asked question on ruby-talk. However, the solution is ugly if you ask me. The canonical solution is to require the 'generator' package and use the SyncEnumerator class.
Blech. I never liked that thing. Too much work for what ought to be a simple thing to do.
Wouldn't it be easier to just modify the Array class? I'm assuming that you're iterating over an Array, mind you, but I think that covers what 99% of most people are doing:
class Array
alias :old_each :each
# Iterate over multiple arrays sequentially
def each(*arrays, &block)
self.old_each(&block)
arrays.old_each{ |array| array.old_each(&block) }
end
# Iterate over two arrays simultaneously
def each_sync(array, &block)
length = array.length > self.length ? array.length : self.length
0.upto(length - 1){ |i| yield self[i], array[i] }
end
end
a = [1, 2, 3]
b = ['a', 'b', 'c']
a.each(b){ p x } # 1 2 3 a b c
a.each_sync(b){ |x,y| puts "#{x} (#{y})" } # 1 (a) 2 (b) 3 (c)