From: Logan Capaldo Date: 2006-03-07T08:26:20+09:00 Subject: Re: What is the best way to iterate through two containers of the same length? --Apple-Mail-25-171560202 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On Mar 6, 2006, at 5:17 PM, Wilson Bilkovich wrote: > > One way I'm fond of is: > require 'generator' > enum = SyncEnumerator.new([1,2,3], [7,8,9]) > enum.each do |pair| > puts pair.inspect > end > # Results in: > [1, 7] > [2, 8] > [3, 9] Warning, SyncEnumerator is slow, and you probably don't need it since #zip is in enumerable. Run the below for a demonstration. Original I had it run each benchmark 10 times by the way, but I never had the patience to let the syncenum versions finish: % cat zip_vs_syncenum.rb require 'benchmark' require 'generator' a = (1..100) b = a.to_a.reverse puts "Using zip:" Benchmark.bm { |x| x.report { 3.times { a.zip(b) { |x, y| z = x * y } } } } puts "Using SyncEnumerator(new every time):" Benchmark.bm { |x| x.report { 3.times { a_b_enum = SyncEnumerator.new(a, b) a_b_enum.each { |x, y| z = x * y } } } } puts "Using SyncEnumerator(only one created):" Benchmark.bm { |x| x.report { a_b_enum = SyncEnumerator.new(a, b) 3.times { a_b_enum.each { |x, y| z = x * y } } } } __END__ --Apple-Mail-25-171560202--