When values are all shaped, sort by the values of the hash:
h = {'a' = =1,'b ' ==2,'C ' +5,'d' = 4}
H.sort {|a,b| a[1]<=>b[1]}
Output: [["a", 1], ["b", 2], ["D", 4], ["C", 5]]
When we need to sort the hash, we cannot use the Sort method as simple as the array, because the data types in the array are the same (integer), the data types in the hash may not be the same, such as the integer type and the string type can not be sorted together, we need to deal with this time, The following (if the data types in the hash are all the same, do not do the following):
def sorted_hash (Ahash)
Return ahash.sort{
|a,b| a.to_s <=> b.to_s
}
End
H1 = {1=> ' one ', 2=> ' one ', 3=> ' three '}
H2 = {6=> ' Six ', 5=> ' five ', 4=> ' four '}
H3 = {' One ' = ' A ', ' One ' and ' B ', ' three ' = ' C '}
h4 = H1.merge (H2) #合并hash
h5 = H1.merge (h3)
def sorted_hash (Ahash)
return ahash.sort{|a,b| a.to_s <=> b.to_s}
End
P (H4)
P (H4.sort)
P (h5)
P (Sorted_hash (h5))
----------------Result---------------
{5=> "Five", 6=> "six", 1=> "one", 2=> "one", 3=> "three", 4=> "four"}
[1, "one"], [2, "one"], [3, "three"], [4, "four"], [5, "Five"], [6, "six"]]
{"One" = "B", "three" = "C", 1=> "one", 2=> "one", "one" = "A", 3=> "three"}
[1, "one"], [2, "one"], [3, "three"], ["One", "A"], ["Three", "C"], ["" "," "B"]]
In fact, the sort method of hash is to convert a hash object into an array with [Key,value] as a single element, and then sort the array using the Sort method.
Hash sorting in Ruby