Sort A Hash By Its Values In Ruby
Use sort_by to order a hash’s key-value pairs by value, returning a sorted array of pairs that can be converted back to a hash.
Description
Hash#sort_by iterates over key-value pairs and sorts them based on the block’s return value. The result is an array of [key, value] pairs. Use Array#to_h (or Hash[]) to convert back to a hash. Ruby hashes preserve insertion order since 1.9, so converting back gives a hash sorted by value.
For descending order, negate a numeric value or call .reverse on the result. For case-insensitive sorting of string values, downcase in the block.
Sample input:
scores = { alice: 85, bob: 92, carol: 78, dave: 92 }
Sample Output:
{ carol: 78, alice: 85, bob: 92, dave: 92 }
Answer
scores = { alice: 85, bob: 92, carol: 78, dave: 92 }
# Sort ascending by value
scores.sort_by { |_, v| v }.to_h
# => { carol: 78, alice: 85, bob: 92, dave: 92 }
# Sort descending by value
scores.sort_by { |_, v| -v }.to_h
# => { bob: 92, dave: 92, alice: 85, carol: 78 }
# Sort string values case-insensitively
names = { c: "Charlie", a: "alice", b: "Bob" }
names.sort_by { |_, v| v.downcase }.to_h
# => { a: "alice", b: "Bob", c: "Charlie" }
# Sort by value, break ties with key
scores.sort_by { |k, v| [v, k.to_s] }.to_h
# => { carol: 78, alice: 85, bob: 92, dave: 92 }
# Get top N values
scores.max_by(2) { |_, v| v }.to_h
# => { bob: 92, dave: 92 }
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀