How to sort a Ruby Hash alphabetically by keys

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

    Ruby's Hash remembers its insertion order now days, but earlier Rubies < v1.9 don't. But, don't bother sorting a hash as there is no advantage to doing so because basically a Hash is a random-access structure. That means the elements are all accessible at any time and it won't make a difference whether one is first or last, you can access it just the same.

    That's unlike an Array which acts like a sequential/text file or a chain or a queue and you have to access it linearly by iterating over it, which, at that point, the order of the elements makes a big difference.

    So, with a Hash, get the keys, sort them, and either iterate over the list of keys or use values_at to retrieve all the values at once. For instance:

    hash = {
        'z' => 9,
        'a' => 1
    }
    
    sorted_keys = hash.keys.sort # => ["a", "z"]
    sorted_keys.each do |k|
      puts hash[k]
    end
    # >> 1
    # >> 9
    
    hash.values_at(*sorted_keys) # => [1, 9]
    

    Some languages won't even let you sort the hash, and accessing it via a sorted list of keys is the only way to extract the elements in an order, so it's probably a good idea to not get in the habit of relying on order of the key/value pairs, and instead rely on the keys.

提交回复
热议问题