Ruby Sorting in Depth
The beginner course sorted lists with sort. sort_by sorts by a value computed from each item.
Sort words by length
sort_by compares the block results instead of the items themselves. Here the key is the length of each word.
words = ["banana", "fig", "apple", "kiwi"]
sorted = words.sort_by { |w| w.length }
p sortedTwo keys settle ties
The key can be an array of two values. Items compare by the first value, and equal first values compare by the second value.
words = ["pear", "plum", "fig", "kiwi"]
sorted = words.sort_by { |w| [w.length, w] }
p sortedPick one winner with min_by and max_by
min_by and max_by each return a single item. Each method compares the keys from its block and keeps one winner.
words = ["apple", "fig", "banana"]
puts words.min_by { |w| w.length }
puts words.max_by { |w| w.length }Sort the pairs of a hash
A hash gives its pairs to sort_by one at a time. Sorting by the second value of each pair orders the pairs by amount.
stock = { "pens" => 30, "books" => 5, "bags" => 12 }
sorted = stock.sort_by { |pair| pair[1] }
p sortedExample
players = { "Ana" => 40, "Ben" => 15, "Cid" => 25 }
ranked = players.sort_by { |pair| pair[1] }
p ranked
best = players.max_by { |pair| pair[1] }
puts best[0]Key points
- sort_by orders items by the block result.
- The block result is called the sort key.
- sort_by returns a new sorted array.
- min_by returns the item with the smallest key.
- max_by returns the item with the biggest key.
- Pairs from a hash can be sorted by their values.
In this example, sort_by orders the player pairs by their scores. The lowest score comes first in the new array. max_by then picks the pair with the highest score, and the last line prints the name from that pair.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ["ccc", "a", "bb"].sort_by { |w| w.length } return?