Sorting helps organize data in a way that makes it easier to find or understand. sort_by lets you decide exactly how to sort things based on your own rules.
Sort_by for custom sorting in Ruby
Introduction
Syntax
Ruby
array.sort_by { |item| expression }The block inside { } tells Ruby what to use for sorting each item.
The original array is not changed; sort_by returns a new sorted array.
Examples
Ruby
names = ["Bob", "Alice", "Eve"] sorted = names.sort_by { |name| name.length }
Ruby
numbers = [5, 2, 9, 1] sorted = numbers.sort_by { |num| -num }
Ruby
people = [{name: "Bob", age: 30}, {name: "Alice", age: 25}]
sorted = people.sort_by { |person| person[:age] }Sample Program
This program sorts a list of fruits by the length of their names and prints the sorted list.
Ruby
fruits = ["apple", "banana", "pear", "kiwi"] sorted_fruits = fruits.sort_by { |fruit| fruit.length } puts sorted_fruits
Important Notes
If two items have the same sorting value, their order stays the same as in the original list (stable sort).
Use sort_by when sorting by a single property or calculation for better speed than sort with a block.
Summary
sort_by sorts items based on a value you choose for each item.
It returns a new sorted array without changing the original.
Use it to sort by length, age, price, or any custom rule you want.
Practice
1. What does the Ruby method
sort_by do?easy
Solution
Step 1: Understand the purpose of
sort_bysort_bysorts elements by a value you choose for each element, like length or age.Step 2: Compare with other array methods
Unlikesort!,sort_byreturns a new sorted array without changing the original.Final Answer:
Sorts elements based on a value you specify for each element. -> Option AQuick Check:
sort_by sorts by chosen value [OK]
Hint: Remember: sort_by sorts by a custom value, not in-place [OK]
Common Mistakes:
- Thinking sort_by changes the original array
- Confusing sort_by with reverse or uniq
- Assuming sort_by removes duplicates
2. Which of the following is the correct syntax to sort an array
words by their length using sort_by?easy
Solution
Step 1: Recall Ruby block syntax for sort_by
The correct syntax uses a block with curly braces and a block variable:array.sort_by { |item| expression }.Step 2: Match syntax with the options
words.sort_by { |word| word.length } correctly useswords.sort_by { |word| word.length }. Others have syntax errors or wrong usage.Final Answer:
words.sort_by { |word| word.length } -> Option CQuick Check:
sort_by needs a block with |variable| [OK]
Hint: Use curly braces and |var| for sort_by blocks [OK]
Common Mistakes:
- Passing arguments directly instead of using a block
- Using => instead of block braces
- Misplacing parentheses around block
3. What will be the output of this Ruby code?
people = [{name: "Anna", age: 30}, {name: "Bob", age: 25}, {name: "Cara", age: 35}]
sorted = people.sort_by { |person| person[:age] }
puts sorted.map { |p| p[:name] }medium
Solution
Step 1: Understand sorting by age
The array is sorted by the :age key in ascending order: 25, 30, 35.Step 2: Map sorted array to names
After sorting, the order is Bob (25), Anna (30), Cara (35). Mapping names gives ["Bob", "Anna", "Cara"].Final Answer:
["Bob", "Anna", "Cara"] -> Option BQuick Check:
sort_by age ascending = [Bob, Anna, Cara] [OK]
Hint: Sort_by returns new array sorted by block value [OK]
Common Mistakes:
- Assuming sort_by sorts descending by default
- Confusing keys in hash access
- Not mapping to names after sorting
4. Identify the error in this code snippet:
items = ["apple", "pear", "banana"] sorted = items.sort_by do |item| item.length end puts sorted
medium
Solution
Step 1: Check block syntax
The block usesdo |item| ... end, which is valid for sort_by.Step 2: Verify sort_by usage
sort_by accepts a block and returns a new array sorted by item length. No syntax or logic errors.Final Answer:
No error; code works correctly -> Option AQuick Check:
sort_by with do-end block is valid [OK]
Hint: do-end blocks work fine with sort_by [OK]
Common Mistakes:
- Thinking parentheses are mandatory around block
- Confusing sort_by with sort!
- Assuming sort_by modifies original array
5. Given an array of hashes representing products:
products = [
{name: "Pen", price: 1.5, stock: 10},
{name: "Notebook", price: 2.0, stock: 0},
{name: "Eraser", price: 0.5, stock: 5}
]
How would you use sort_by to get products sorted by price but only include those with stock greater than zero?hard
Solution
Step 1: Filter products with stock > 0
Useselectto keep only products wherestockis greater than zero.Step 2: Sort filtered products by price
Applysort_byon the filtered array to sort byprice.Final Answer:
products.select { |p| p[:stock] > 0 }.sort_by { |p| p[:price] } -> Option DQuick Check:
Filter then sort_by for correct result [OK]
Hint: Filter first, then sort_by for combined conditions [OK]
Common Mistakes:
- Trying to filter inside sort_by block
- Sorting by stock instead of price
- Selecting after sorting, which keeps unwanted items
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
