0
0
RubyHow-ToBeginner · 3 min read

How to Sort Hash by Value in Ruby: Simple Guide

In Ruby, you can sort a hash by its values using hash.sort_by { |key, value| value }. This returns an array of key-value pairs sorted by the values in ascending order.
📐

Syntax

The basic syntax to sort a hash by its values is:

hash.sort_by { |key, value| value }

Here, hash is your original hash. The sort_by method takes a block where you specify to sort by the value part of each key-value pair.

This returns an array of arrays, where each inner array contains a key and its value, sorted by the value.

ruby
sorted_array = hash.sort_by { |key, value| value }
💻

Example

This example shows how to sort a hash of fruits and their quantities by the quantity values in ascending order.

ruby
fruits = { apple: 5, banana: 2, cherry: 7, date: 3 }
sorted_fruits = fruits.sort_by { |key, value| value }
puts sorted_fruits.inspect
Output
[[:banana, 2], [:date, 3], [:apple, 5], [:cherry, 7]]
⚠️

Common Pitfalls

1. Expecting a Hash as output: sort_by returns an array of pairs, not a hash. To get a hash back, you can convert it using to_h.

2. Sorting by key instead of value: Make sure the block uses value to sort by values, not key.

3. Modifying the original hash: Sorting does not change the original hash; it returns a new sorted array or hash.

ruby
fruits = { apple: 5, banana: 2 }

# Wrong: sorting by key instead of value
wrong_sort = fruits.sort_by { |key, value| key }

# Right: sorting by value
right_sort = fruits.sort_by { |key, value| value }

# Convert sorted array back to hash
sorted_hash = right_sort.to_h

puts wrong_sort.inspect
puts right_sort.inspect
puts sorted_hash.inspect
Output
[[:apple, 5], [:banana, 2]] [[:banana, 2], [:apple, 5]] {:banana=>2, :apple=>5}
📊

Quick Reference

  • Sort by value ascending: hash.sort_by { |k, v| v }
  • Sort by value descending: hash.sort_by { |k, v| -v } (works if values are numbers)
  • Convert sorted array back to hash: .to_h

Key Takeaways

Use sort_by { |key, value| value } to sort a hash by its values in Ruby.
The result of sorting is an array of key-value pairs, not a hash.
Convert the sorted array back to a hash with .to_h if needed.
To sort descending, negate numeric values inside the block.
Sorting does not modify the original hash; it returns a new sorted collection.