The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Iterating over multiple arrays

1 reply on 1 page. Most recent reply: Mar 29, 2006 4:55 PM by Trans Onoma

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
Iterating over multiple arrays Posted: Mar 29, 2006 4:40 PM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
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)

Yes? No? Brilliant? Stupid?

Read: Iterating over multiple arrays


Trans Onoma

Posts: 63
Nickname: transfire
Registered: Aug, 2005

Re: Iterating over multiple arrays Posted: Mar 29, 2006 4:55 PM
Reply to this message Reply
Why not just use zip?

a = [1,2,3]
b = [4,5,6]
a.zip(b).each { |a,b| ... }

Something like that.

Flat View: This topic has 1 reply on 1 page
Topic: Web services, Rails-style Previous Topic   Next Topic Topic: Refreshing Advice

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use