3

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
rnso
  • 23,686
  • 25
  • 112
  • 234

2 Answers2

5

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")
pjs
  • 18,696
  • 4
  • 27
  • 56
4

Since Crystal Hash preserves order of insertion, it is possible to actually make a sorted Hash:

myhash.to_a.sort.to_h

To sort by values,

myhash.to_a.sort_by { |k, v| v }.to_h

To sort in-place, it's a bit bulkier:

myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}

entries = myhash.to_a.sort
myhash.clear
entries.each { |k, v| myhash[k] = v }
Amadan
  • 191,408
  • 23
  • 240
  • 301