Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Use sort_by in Ruby: Syntax and Examples

In Ruby, sort_by is used to sort elements of a collection by a specific attribute or computed value. You pass a block to sort_by that returns the value to sort by, and it returns a new sorted array.
📐

Syntax

The sort_by method is called on an enumerable collection like an array. You provide a block that tells Ruby what value to use for sorting each element.

  • collection.sort_by { |element| expression }
  • collection: The array or enumerable to sort.
  • element: Each item in the collection.
  • expression: The value used to compare and sort elements.
ruby
sorted_array = collection.sort_by { |element| element.attribute }
💻

Example

This example sorts an array of hashes by the :age key using sort_by. It returns a new array sorted from youngest to oldest.

ruby
people = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Carol", age: 35 }
]
sorted_people = people.sort_by { |person| person[:age] }
puts sorted_people
Output
[{:name=>"Bob", :age=>25}, {:name=>"Alice", :age=>30}, {:name=>"Carol", :age=>35}]
⚠️

Common Pitfalls

One common mistake is using sort instead of sort_by when sorting by a computed value, which can be less efficient. Another is forgetting that sort_by returns a new sorted array and does not modify the original.

Also, if the block returns nil or inconsistent values, sorting may fail or give unexpected results.

ruby
numbers = [10, 2, 33]
# Wrong: sort without block sorts by natural order
puts numbers.sort

# Right: sort_by with block to sort by string length
puts numbers.sort_by { |n| n.to_s.length }
Output
[2, 10, 33] [10, 2, 33]
📊

Quick Reference

MethodDescription
sort_by { |x| ... }Sorts collection by the block's return value, returns new array
sortSorts collection by natural order or block, less efficient for computed keys
sort_by! { |x| ... }Sorts collection in place by block's return value (if supported)
✅

Key Takeaways

Use sort_by to sort collections by a specific attribute or computed value.
sort_by returns a new sorted array and does not change the original.
Always provide a block that returns a consistent value for sorting.
For better performance on complex sorting, prefer sort_by over sort with a block.