From: David Alan Black Date: 2000-11-27T09:09:35+09:00 Subject: [ruby-talk:6584] Re: best way to interleaf arrays? Hello -- On Mon, 27 Nov 2000, Brian F. Feldman wrote: > David Alan Black wrote: > > Hello -- > > > > Is there a nice Ruby idiom for interleafing arrays? It's not hard to > > write a method that will do it, but I'd be interested in knowing how > > it's been done in the past. > > What do you mean by interleave? Normally I'd take this to mean that you'd > want the even number of elements from the first array and the odd numbered > elements to come from the second array, but it seems you're implying you > just want the logical union of the two. e.g. Hmmmm.... I'm not sure what I said that implied that. Maybe throwing in the hash thing was confusing. Anyway, except for my misspelling the word (an old mental glitch), my reference was indeed to interleaving. My current best shot at an interleave method is: class Array def interleave(ary2) a1, a2, res = self.dup, ary2.dup, [] res.push a1.shift, a2.shift until a1.empty? or a2.empty? for n in [a1, a2] res.concat n unless n.empty? end res end end which is about as fast as I can get it (non-destructively :-) On the hash matter: > You can always do it as: > > h = Hash.new(false) > (array1 + array2).each {|x| h[x] = true} Yes, I think that's where the union confusion was. My hash topic was actually separate. I was working on a whole cluster of problems, the connections among which were probably less clear than I'd thought. The problem in the middle, so to speak, was populating a hash from two arrays, in this sense: h = Hash[*a1.interleave(a2)] which set me on the road to interleaving, and also got me wondering about what else could be done between those square brackets (e.g., setting values to true for an array of keys). David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav