Sobes.tech
Junior

What is the sort method in Ruby?

sobes.tech AI

Answer from AI

sort in Ruby is a method used to order elements in a collection (such as an array or range). It returns a new object containing the same elements but in sorted order, leaving the original collection unchanged.

The default sorting is in ascending order, using the comparison operator <=>.

You can provide a block of code to define custom sorting logic. The block takes two elements from the collection and should return:

  • -1 or a negative number if the first element should come before the second.
  • 0 if the elements are considered equal.
  • 1 or a positive number if the first element should come after the second.

Examples of usage:

# Sorting an array of numbers in default (ascending) order
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = numbers.sort # => [1, 1, 2, 3, 4, 5, 6, 9]
# Sorting an array of strings in default (alphabetical) order
fruits = ["banana", "apple", "cherry"]
sorted_fruits = fruits.sort # => ["apple", "banana", "cherry"]
# Sorting in descending order (using a block)
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_desc = numbers.sort { |a, b| b <=> a } # => [9, 6, 5, 4, 3, 2, 1, 1]
# Sorting an array of hashes by a key's value (using a block)
people = [{name: "Alice", age: 30}, {name: "Bob", age: 25}, {name: "Charlie", age: 35}]
sorted_by_age = people.sort { |a, b| a[:age] <=> b[:age] }
# => [{:name=>"Bob", :age=>25}, {:name=>"Alice", :age=>30}, {:name=>"Charlie", :age=>35}]

There is also a mutating version sort! and sort_by / sort_by! for more efficient sorting by key. sort_by computes the key for each element once before sorting.