Array.sort / sort_by / reverse
| Since: | Ruby 1.8(2003) |
|---|
Methods for sorting and reversing arrays. sort sorts in ascending order, sort_by sorts based on the return value of a block, and reverse reverses the order of elements.
Syntax
arr.sort
arr.sort { |a, b| a <=> b }
# Returns a new array sorted by the block's return value as the key.
arr.sort_by { |element| key_value }
# Returns a new array with the elements in reverse order.
arr.reverse
Method List
| Method | Description |
|---|---|
| sort | Returns a new array sorted in ascending order. Passing a block lets you define custom comparison logic. |
| sort_by { |e| ... } | Sorts using the block's return value as the comparison key. Useful for sorting by string length or object attributes. |
| sort! | Sorts the original array in place (destructive method). |
| sort_by! | Sorts the original array in place using the block's key (destructive method). |
| reverse | Returns a new array with the elements in reverse order. |
| reverse! | Reverses the original array in place (destructive method). |
Sample Code
sample_array_sort_sort_by_reverse.rb
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
puts numbers.sort.inspect # [1, 1, 2, 3, 4, 5, 6, 9]
# Sort numbers in descending order (reverse the comparison in the block)
puts numbers.sort { |a, b| b <=> a }.inspect # [9, 6, 5, 4, 3, 2, 1, 1]
# Sort strings alphabetically
names = ['Melon', 'Cherry', 'Apple', 'Strawberry']
puts names.sort.inspect # ["Apple", "Cherry", "Melon", "Strawberry"]
# Sort strings by length
puts names.sort_by { |w| w.length }.inspect # ["Melon", "Apple", "Cherry", "Strawberry"]
# Sort an array of hashes by a specific key
people = [
{ name: 'member_a', age: 25, dept: 'sales' },
{ name: 'member_b', age: 22, dept: 'sales' },
{ name: 'member_c', age: 28, dept: 'engineering' }
]
sorted = people.sort_by { |p| p[:age] }
sorted.each { |p| puts "#{p[:name]}: #{p[:age]}" }
# Output order: member_b: 22, member_a: 25, member_c: 28
# Reverse an array
puts [1, 2, 3, 4, 5].reverse.inspect # [5, 4, 3, 2, 1]
puts 'hello'.chars.reverse.join # olleh (a trick for reversing a string)
# Destructive method (modifies the original array)
arr = [5, 3, 1, 4, 2]
arr.sort!
puts arr.inspect # [1, 2, 3, 4, 5] (the original array has been modified)
Running the code produces the following output:
ruby array_sort_sort_by_reverse.rb [1, 1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1, 1] ["Apple", "Cherry", "Melon", "Strawberry"] ["Melon", "Apple", "Cherry", "Strawberry"] member_b: 22 member_a: 25 member_c: 28 [5, 4, 3, 2, 1] olleh [1, 2, 3, 4, 5]
Overview
sort compares elements using the <=> (spaceship operator). By passing a block that returns -1, 0, or 1, you can sort in descending order or apply multi-condition sorting.
sort_by uses the block's return value as the comparison key, making it straightforward to sort complex objects. For large datasets, sort_by is more efficient than sort. This is because the block is called fewer times overall.
Methods ending with ! modify the original array directly. Use the non-destructive versions when you need to preserve the original data. To sort by multiple keys, a useful technique is to return an array from the block (e.g., sort_by { |e| [e[:age], e[:name]] }).
If you find any errors or copyright issues, please contact us.