How to sort a Ruby Hash alphabetically by keys

前端 未结 5 1403
长发绾君心
长发绾君心 2021-02-05 05:32

I am trying to sort a Hash alphabetically by key, but I can\'t seem to find a way to do it without creating my own Sorting class. I found the code below to sort by value if it\'

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 06:22

    Assuming you want the output to be a hash which will iterate through keys in sorted order, then you are nearly there. Hash#sort_by returns an Array of Arrays, and the inner arrays are all two elements.

    Ruby's Hash has a constructor that can consume this output.

    Try this:

    temp = Hash[ temp.sort_by { |key, val| key } ]
    

    or more concisely

    temp = temp.sort_by { |key| key }.to_h
    

    If your hash has mixed key types, this will not work (Ruby will not automatically sort between Strings and Symbols for instance) and you will get an error message like comparison of Symbol with String failed (ArgumentError). If so, you could alter the above to

    temp = Hash[ temp.sort_by { |key, val| key.to_s } ] 
    

    to work around the issue. However be warned that the keys will still retain their original types which could cause problems with assumptions in later code. Also, most built-in classes support a .to_s method, so you may get unwanted results from that (such as unexpected sort order for numeric keys, or other unexpected types).

    You could, in addition, convert the keys to Strings with something like this:

    temp = Hash[ temp.map { |key, val| [key.to_s, val] }.sort ] 
    

    . . . although this approach would lose information about the type of the original key making it impossible to refer back to the original data reliably.

提交回复
热议问题