How to sort a Ruby Hash alphabetically by keys

前端 未结 5 1387
长发绾君心
长发绾君心 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:15

    sorted_by_key = Hash[original_hash.sort]
    

    will create a new Hash by inserting the key/values of original_hash alphabetically by key. Ruby 2.x hashes remember their insertion order, so this new hash will appear sorted by key if you enumerate it or output it.

    If you insert more elements in a non-alphabetical order, this won't hold of course.

    Also, this assumes the original hash keys are all sortable/comparable.

提交回复
热议问题