Hash sort in Ruby

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.