Skip to content

Instantly share code, notes, and snippets.

@sonkm3
Last active December 20, 2015 08:49
Show Gist options
  • Save sonkm3/6102798 to your computer and use it in GitHub Desktop.
Save sonkm3/6102798 to your computer and use it in GitHub Desktop.
ruby: sort hash by key.
hash1 = {:b => 1, :a => 2}
# => {:b=>1, :a=>2}
Hash[hash1.sort_by{|key, val|key}]
# => {:a=>2, :b=>1}
Hash[hash1.sort]
# => {:a=>2, :b=>1}
# sort by value
Hash[hash1.sort_by{|key, val|val}]
# => {:b=>1, :a=>2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment