From: David Alan Black Date: 2001-04-11T06:28:31+09:00 Subject: [ruby-talk:13599] Re: #U017 "partition" method -- followup Hi -- On Sat, 7 Apr 2001, Guy N. Hurst wrote: > Array#split would make an array of subarrays based on a block: > > [1,2,3,4,5].split{|x| x<=>3} # => [[3],[4,5],[1,2]] > > ary=["an","a","the","when","if","can","do"] > ary.split{|x| x.length } # => [[],["a"],["an","if","do"],["the","can"],["when"]] Here, just for the sake of seeing it (in some form) in action, is an implementation of something close (see further comments): class Array def split results = {} ary2 = [] each do |e| y = yield(e) results[y] ||= ary2.size ary2[results[y]] ||= [] ary2[results[y]].push(e) end ary2 end end [1,2,3,4,5].split{|x| x<=>3} # => [[1, 2], [3], [4, 5]] ary=["an","a","the","when","if","can","do"] ary.split{|x| x.length} # => [["an", "if", "do"], ["a"], ["the", "can"], ["when"]] # (Alternate #each: # each do |e| # (ary2[results[yield(e)] ||= ary2.size] ||= []) .push(e) # end # :-) Obviously my version goes through the array and creates (or appends to) the appropriate subarray based on what it finds, in order. I sense that this might be good, since otherwise the method would have to decide (for instance) that lengths should be returned in ascending order, while spaceships should be returned in x=,x<,x> order (taking your hypothetical output literally). > It could also be made to generate a hash, to allow for block output > other than just numbers: > > ary.split{|x| x[0..0]} # => {"a"=>["an","a"], "t"=>["the"], etc... } Funny -- I've been dealing with something quite like that, where I'm taking a bunch of file names which cluster according to their first four characters and hashing and arraying them in various ways. Anyway, wouldn't this have to be a different method? How would #split (or whatever it's called) know to construct a hash, rather than an array -- and, come to think of it, would one really want it returning different types depending on the input? David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav