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\'
In addition to Neil Slater's answer, which uses the Hash#sort_by
method (which is nice and concise when outputting comparable values in the block)...
irb(main):001:0> h = { a: 0, b: 5, c: 3, d: 2, e: 3, f:1 }
=> {:a=>0, :b=>5, :c=>3, :d=>2, :e=>3, :f=>1}
irb(main):002:0> h.sort_by { |pair| pair[1] }.to_h
=> {:a=>0, :f=>1, :d=>2, :c=>3, :e=>3, :b=>5}
...or the reverse variant...
irb(main):003:0> h.sort_by { |pair| pair[1] }.reverse.to_h
=> {:b=>5, :e=>3, :c=>3, :d=>2, :f=>1, :a=>0}
...there is also the option to use the Array#sort
method which allows you to define your own comparison rules (e.g. this sorts by value ascending, but then by key descending on equal values):
irb(main):004:0> h.to_a.sort { |one, other| (one[1] == other[1]) ? other[0] <=> one[0] : one[1] <=> other[1] }.to_h
=> {:a=>0, :f=>1, :d=>2, :e=>3, :c=>3, :b=>5}
This last option is a bit less concise, but can be more flexible (e.g. custom logic to deal with a mixture of types).