views:

62

answers:

3

Is it possible conditional sort in hash

my hash like {1=>"10",2=>"20",3=>"30",4=>"40",5=>"50",6=>"60",7=>"70",8=>"80",9=>"90"}

wanted result is

{7=>"70",8=>"80",9=>"90",1=>"10",2=>"20",3=>"30",4=>"40",5=>"50",6=>"60"}

add condition in this code

operation_hour_hash.sort{|key,value| key[1]<=>value[1]}
+1  A: 

Your sort call is misleading. You are not comparing key and value, you are comparing two different elements of an array. So it should be:

operation_hour_hash.sort{|a,b| a[1]<=>b[1]}

You can implement whatever logic you want in a sort block, as long as it adheres to following:

The block implements a comparison between a and b, returning -1, 0, or +1

(taken from: http://ruby-doc.org/core/classes/Array.html#M002185)

Slobodan Kovacevic
+3  A: 

Sure, you could do something like:

>> {1=>"10",2=>"20",3=>"30",4=>"40",5=>"50",6=>"60",7=>"70",8=>"80",9=>"90"}.sort{|p,n| (p[1].to_i>=70 && n[1].to_i<70) ? -1 : (p[1].to_i<70 && n[1].to_i>=70) ? 1 : p[1].to_i <=> n[1].to_i}

=> [[7, "70"], [8, "80"], [9, "90"], [1, "10"], [2, "20"], [3, "30"], [4, "40"], [5, "50"], [6, "60"]]

But, sorting a hash doesn't really make much sense. Before the sort actually takes place it's converted to an array of [key,value] pairs then sorted by -1,0,1 returned from <=>.

If you need sorted hashes you'll need to use something like RubyFacets Dictionary class.

jdeseno
+1  A: 

You can try something like this to produce a sorted array

operation_hour_hash.sort {|x,y| (x[0]>6?x[0]-6:x[0]+24)<=>(y[0]>6?y[0]-6:y[0]+24)}
>>  [[7, "70"], [8, "80"], [9, "90"], [1, "10"], [2, "20"], [3, "30"], [4, "40"], [5, "50"], [6, "60"]]

You can change the conditions to suit your needs.

However be careful that in ruby 1.8, a hash is not ordered by the key. If you convert back to hash, the order is not guaranteed.

Zaki