Created
April 27, 2015 00:23
-
-
Save streetcarmonkey/880b096b5c4c057aedbd to your computer and use it in GitHub Desktop.
How to sort a hash by nested hash values in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Courtesy of http://www.rubyinside.com/how-to/ruby-sort-hash | |
# I added the reverse (descending) sort part at the bottom. | |
# Sample Data | |
people = { | |
:fred => { :name => "Fred", :age => 23 }, | |
:joan => { :name => "Joan", :age => 18 }, | |
:pete => { :name => "Pete", :age => 54 } | |
} | |
# Sort ascending | |
p people.sort_by { |k, v| v[:age] } | |
# => [[:joan, {:name=>"Joan", :age=>18}], | |
# [:fred, {:name=>"Fred", :age=>23}], | |
# [:pete, {:name=>"Pete", :age=>54}]] | |
# Sort descending | |
p people.sort_by { |k, v| v[:age] }.reverse! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment