hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Friday

2006.01.27

ary / 3 #

by why in bits

Sometimes I wish Array.partition could split into more than halves. Something like partition_by or commonality. Like an Array./ method!

 class Array
   def / len
     inject([]) do |ary, x|
       ary << [] if [*ary.last].nitems % len == 0
       ary.last << x
       ary
     end
   end
 end

 >> products = %w[cycles vents hoops willies moogs rifles pools fawns tridents]
 >> products / 3
 => [["cycles", "vents", "hoops"], ["willies", "moogs", "rifles"], 
     ["pools", "fawns", "tridents"]]
 >> products / 2
 => [["cycles", "vents"], ["hoops", "willies"], 
     ["moogs", "rifles"], ["pools", "fawns"], ["tridents"]]

The other alternative being a hopscotch with a flip-flop.