From: 7stud -- Date: 2008-02-07T09:03:40+09:00 Subject: Re: Array Practice 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. Another way would be to iterate over your original array and add each number to a Hash as you go. A Hash keys will be one of the numbers, and the corresponding value will be an array containing all of that particular number. You can create a new Hash so that when you access a non existent key in a Hash an empty array will be returned. See the block form of Hash.new(). Finally, you can create your final array from the hash values using Hash#values. -- Posted via http://www.ruby-forum.com/.