From: "Jan E." Date: 2012-06-18T13:55:09+09:00 Subject: Re: Overwriting one Ruby array or arrays with another Hi, I think it's generally better to open a new thread if you've got a new question. Then we don't have to sort out the old postings. Craig Law wrote in post #1064927: > Has anyone got any suggestions on how I can achieve an ordered array > that looks like this ... > > [[1, 3, "X","20120609"], [2, 3, "X","20120610"], [3, 3, "X","20120611"], > [1, 2, "X","20120612"], [2, 2, "X","20120613"], [3, 2, "X","20120614"], > [1, 1, "X","20120615"], [2, 1, "X","20120616"], [3, 1, "X","20120617"]] > > Many thanks > > Craig The "sort" method lets you supply a block. The elements will be passed to the block two at a time and compared according to the return value (which is supposed to be either -1, 0 or 1, following the logic of the <=> method). If this case, you first compare the x coordinates. If they're different, then the result of the comparison is the overall result. If they're the same, you compare the values by the y coordinates (in reverse order): #--------------- hash1 = { [1, 3] => ["X","20120609"], [3, 3] => ["X","20120610"], [2, 1] => ["X","20120611"], [1, 2] => ["X","20120612"], [3, 2] => ["X","20120613"], [3, 1] => ["X","20120614"], [1, 3] => ["X","20120615"], [2, 1] => ["X","20120616"], [2, 2] => ["X","20120617"] } sorted_keys = hash1.keys.sort do |(x1, y1), (x2, y2)| x_comparison = x1 <=> x2 if x_comparison != 0 x_comparison else y2 <=> y1 # note the reverse order end end p sorted_keys #--------------- You may also shorten the block content to [x1 <=> x2, y2 <=> y1].find &:nonzero? This will select the first of the two comparisons which is not 0. -- Posted via http://www.ruby-forum.com/.