ruby-lang
March 8th, 2006, 06:20 PM
<p>Sometimes I wish <code>Array.partition</code> could split into more than halves. Something like <a href="http://facets.rubyforge.org/rdoc-nano/classes/Enumerable.html#M000432">partition_by</a> or <a href="http://facets.rubyforge.org/rdoc-nano/classes/Enumerable.html#M000451">commonality</a>. Like an <code>Array./</code> method!</p>
<pre>
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"]]
</pre>
<p>The other alternative being a <a href="http://redhanded.hobix.com/inspect/hopscotchingArraysWithFlipFlops.html">hopscotch with a flip-flop</a>.</p>
<a href="http://redhanded.hobix.com/bits/matchingIntoMultipleAssignment.html" target="_blank">http://redhanded.hobix.com/bits/matchingIntoMultipleAssignment.html</a>
<pre>
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"]]
</pre>
<p>The other alternative being a <a href="http://redhanded.hobix.com/inspect/hopscotchingArraysWithFlipFlops.html">hopscotch with a flip-flop</a>.</p>
<a href="http://redhanded.hobix.com/bits/matchingIntoMultipleAssignment.html" target="_blank">http://redhanded.hobix.com/bits/matchingIntoMultipleAssignment.html</a>