From: Todd Benson Date: 2007-06-19T03:41:05+09:00 Subject: Re: Adding new value (in array) to existing key in a hash On 6/18/07, Gilbert Lau wrote: > Thanks a million. But still I have another problem. Figure that I can > take it on from all your guys' help, but I can't. > > A more controlled sort. I only want to sort the keys where the values > from myhash follows this pattern of [i,j], [i+1,j+1]... think of it as > a 2-D matrix and I am only interested in the diagonal line. I am not > worried about the duplicates of coordinates, as one coordinates can only > have one occurrence(or building). > > For example, the sorted result for the following hash will be: > > myhash = {"a"=>[[0, 0], [3, 4]], "b"=>[[1, 1], [9, 8]], "c"=>[[7, 6],[4, > 5]} > > [[0, 0], [1, 1], [3, 4], [4, 5]] > "a", "b", "a", "c" Do you mean that [7,6] is not included becuase there is no [6,5] or [8,7]? You shouldn't open up core classes and you don't have to for this, but it makes it more readable: class Array def up; map {|i| i+1}; end def down; map {|i| i-1}; end end h = { "a" => [[0,0],[3,4]], "b" => [[1,1],[9,8]], "c" => [[7,6],[4,5]] } a = [] h.each_value {|v| v.each {|coord| a << coord}} end sorted = a.select {|coord| a.include?(coord.up) || a.include?(coord.down) )}.sort p sorted