From: MonkeeSage Date: 2007-12-16T19:05:02+09:00 Subject: Re: An idiomatic way to traverse all pairs in an enumerable? On Dec 15, 6:25 pm, Rob Biedenharn wrote: > On Dec 15, 2007, at 6:03 PM, Shot (Piotr Szotkowski) wrote: > > > > > I seem to end up doing the following quite a lot: > > > enum.each do |a| > > enum.each do |b| > > next if a >= b > > # do_something with a and b > > end > > end > > > In general, I'm looking for an idiomatic way of traversing each > > possible pair of a given enum's contents (once). Is there a more > > compact construct? > > > (I assume I could finally grasp the whole block-passing side of Ruby > > and write my own Enumerable#each_mix, but maybe there's something > > there > > already. Note: Enumerable#each_pair doesn't cut it, as it's just for > > neighbouring element pairs, while I need something for all possible > > pairs.) > > > Thanks in advance for any help with the above! > > > -- Shot > > -- > > The existential root of libertarianism is the experience of > > being very bad at taking orders from morons. -- Leopold Leider > > http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/42671 > > You could use the Array#combination code posted there either directly > or as an example. If you can rely on the ordering of elements (your > a>=b), your code isn't too bad, but the code on the ruby list will be > (is) part of Ruby1.9 and only depends on position within the Array. > If you have an enumerable that's not an Array, you might have some > tweaking to do anyway. > > -Rob > > Rob Biedenharn http://agileconsultingllc.com > R...@AgileConsultingLLC.com module Enumerable def every_pair(other) self.each { | x | other.each { | y | yield [x, y] if x < y } } end end a = [1, 8, 3] b = [4, 5, 6] a.every_pair(b) { | x, y | puts "doing stuff with " + [x, y].inspect } # => doing stuff with [1, 4] doing stuff with [1, 5] doing stuff with [1, 6] doing stuff with [3, 4] doing stuff with [3, 5] doing stuff with [3, 6] Regards, Jordan