Search code examples
dictionaryhashtablecrystal-lang

Can Hash be sorted by keys or values?


Is it possible to sort Hash by key or by value in following code:

myhash.each_key do |key| 
   print myhash[key], "\t:\t", key, "\n" 
end

Solution

  • Sorting by keys:

    myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}
    
    myhash.keys.sort.each do |key| 
      print myhash[key], "\t:\t", key, "\n" 
    end
    

    produces

    one     :   1
    two     :   2
    three   :   3
    four    :   4
    five    :   5
    

    Sorting by value is a bit more effort:

    myhash.to_a.sort { |item1, item2| item1[1] <=> item2[1] }.each do |item|
      puts item.join("\t:\t")
    end
    

    produces

    5   :   five
    4   :   four
    1   :   one
    3   :   three
    2   :   two
    

    If you want the outcomes in value:key order, change

    puts item.join("\t:\t")
    

    to

    puts item.reverse.join("\t:\t")