Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

7.9. Looping Through Multiple Iterables in Parallel

Problem

You want to traverse multiple iteration methods simultaneously, probably to match up the corresponding elements in several different arrays.

Solution

The SyncEnumerator class, defined in the generator library, makes it easy to iterate over a bunch of arrays or other Enumerable objects in parallel. Its each method yields a series of arrays, each array containing one item from each underlying Enumerable object:

	require 'generator'

	enumerator = SyncEnumerator.new(%w{Four seven}, %w{score years},
	                                %w{and ago})
	enumerator.each do |row|
	  row.each { |word| puts word }
	  puts '---'
	end
	# Four
	# score
	# and
	# ---
	# seven
	# years
	# ago
	# ---

	enumerator = SyncEnumerator.new(%w{Four and}, %w{score seven years ago})
	enumerator.each do |row|
	  row.each { |word| puts word }
	  puts '---'
	end
	# Four
	# score
	# ---
	# and
	# seven
	# ---
	# nil
	# years
	# ---
	# nil
	# ago
	# ---

You can reproduce the workings of a SyncEnumerator by wrapping each of your Enumerable objects in a Generator object. This code acts like SyncEnumerator#each, only it yields each individual item instead of arrays containing one item from each Enumerable:

	def interosculate(*enumerables) 
generators = enumerables.collect { |x|  
Generator.new(x) }
	  done = false
	  until done
	    done = true
	    generators.each do |g|
	      if g.next?
	        yield g.next
	        done = false
	      end
	    end
	  end
	end

	interosculate(%w{Four and}, %w{score seven years ago}) do |x|
	  puts x
	end
	# Four
	# score
	# and
	# seven
	# years
	# ago

Discussion ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required