Sort hash by key, return hash in Ruby

Vincent picture Vincent · Dec 2, 2010 · Viewed 186.8k times · Source

Would this be the best way to sort a hash and return Hash object (instead of Array):

h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
# => {"a"=>1, "c"=>3, "b"=>2, "d"=>4}

Hash[h.sort]
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4}

Answer

Mark Thomas picture Mark Thomas · Mar 11, 2014

In Ruby 2.1 it is simple:

h.sort.to_h