From: Rob Biedenharn Date: 2008-02-07T08:49:33+09:00 Subject: Re: Array Practice On Feb 6, 2008, at 6:20 PM, Adam Akhtar wrote: > As some of you may know from previous threads im trying to practice > specific areas of ruby. One simple exercise i set myself was taking a > elements in an array such as > > [1,2,3,1,2,2,4,3,2,1] > > and then grouping them together and putting them in subarrays within > an > array like this > > [ [1,1,1], [2,2,2,2] , [3,3] ,[4] ] > > Heres how i did it (im new to both programming and ruby) > > def subpack(list) > uniqlist = Array.new > subpacklist = Array.new > list.sort! > > uniqlist = list.uniq > uniqlist.each_index do |i| > rangeleft = list.index(uniqlist[i]) > rangeright = list.rindex(uniqlist[i]) > subpacklist << list.slice(rangeleft..rangeright) > end > subpacklist > end > > > WITHOUT GIVING ME YOUR SOLUTION IN FULL, how could i improve this... > i.e. give me some hints, the names of some methods but not the > solution > as i want a go myself. Think about how you might do it with a pencil... - write the values out in order "[ 1, 1, 1, 2, 2, 2, 2, 3, 3, 4 ]" - if the "next" value is different from the last value processed (and initially there is no last value), then start a new sub-array with this single value (my pencil would insert a '[' between the '[' and '1') - ...and if you'd already written a '[', you have to then write "],[" - if the next value is the same, move your pencil (since it goes in the current sub-array) - when you run out of values, close the final subarray with ']' It shouldn't take much to think about how this turns into Ruby (keeping in mind that Arrays are always finite so you don't really have to "write" the ']') -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com