William James wrote: > > I am a Ruby newbie and would appreciate a critique on the method I > > posted. > > > > Thank You > > class Array > def split n > count , fat_ones = self.size / n , self.size % n > self.inject( [[]] ){ |a,e| > a.last.size < count + ( a.size <= fat_ones ? 1 : 0 ) ? > a.last << e : a << [e] ; a } > end > end > > a = (1..23).to_a > p a.split(5) > p a Yes! it is a much better way !!! Since obviously I am not familiar with the inject method, I took to the pick axe and irb to work it out until I understood exactly what you were doing. The only question left is how to best handle bad inputs? n <= 0, n not specified, and an empty array, n > [1,2,3,4,5].size for [1,2,3,4,5].split(0) => Exception: divided by 0 for [1,2,3,4,5].split(-n) => [[], [1], [2], [3], [4], [5]] for [].split(+/-n) => [[]] where n != 0 for [].split(0) => Exception: divided by 0 for [1,2,3,4,5].split() => Exception: wrong number of arguments (0 for 1) for [1,2,3,4,5].split(8) => [[1], [2], [3], [4], [5]] I would guess this might be the correct way. This could cause a problem if the user were to check the size of the returned array For the above example it would be5 instead of the expected 8. You could say that for n == 0 or n not specifiend are already handled by existing Exceptions. Do need to handle negative values of n, n > array.size and array.size == 0