0
0
RubyHow-ToBeginner · 3 min read

How to Sort Array in Ruby: Simple Syntax and Examples

In Ruby, you can sort an array using the sort method, which returns a new sorted array. To sort the original array in place, use sort!. Both methods work on arrays of numbers, strings, or any objects that can be compared.
📐

Syntax

The basic syntax to sort an array is using array.sort, which returns a new sorted array without changing the original. To sort the array itself, use array.sort!. You can also provide a block to customize sorting order.

  • array.sort: returns a new sorted array.
  • array.sort!: sorts the array in place.
  • array.sort { |a, b| ... }: custom sorting logic.
ruby
array = [3, 1, 4, 2]
sorted_array = array.sort
array.sort! # sorts in place
💻

Example

This example shows how to sort an array of numbers and an array of strings. It also demonstrates sorting in ascending and descending order.

ruby
numbers = [5, 2, 9, 1]
strings = ["banana", "apple", "cherry"]

# Sort numbers ascending
sorted_numbers = numbers.sort
puts sorted_numbers.inspect

# Sort strings ascending
sorted_strings = strings.sort
puts sorted_strings.inspect

# Sort numbers descending using block
descending_numbers = numbers.sort { |a, b| b <=> a }
puts descending_numbers.inspect
Output
[1, 2, 5, 9] ["apple", "banana", "cherry"] [9, 5, 2, 1]
⚠️

Common Pitfalls

One common mistake is expecting sort to change the original array, but it returns a new sorted array instead. Use sort! to sort in place. Another pitfall is forgetting that sorting strings is case-sensitive by default, which can lead to unexpected order.

ruby
arr = ["b", "A", "c"]

# Wrong: expecting original array to change
arr.sort
puts arr.inspect  # Output: ["b", "A", "c"] (unchanged)

# Right: sort in place
arr.sort!
puts arr.inspect  # Output: ["A", "b", "c"]

# Case-insensitive sort
arr = ["b", "A", "c"]
sorted_case_insensitive = arr.sort { |a, b| a.downcase <=> b.downcase }
puts sorted_case_insensitive.inspect  # Output: ["A", "b", "c"]
Output
["b", "A", "c"] ["A", "b", "c"] ["A", "b", "c"]
📊

Quick Reference

Here is a quick summary of Ruby array sorting methods:

MethodDescription
array.sortReturns a new sorted array, original unchanged.
array.sort!Sorts the array in place, modifying the original.
array.sort { |a, b| ... }Sorts with custom comparison logic.
array.sort_by { |item| ... }Sorts by computed values for each item.

Key Takeaways

Use sort to get a new sorted array without changing the original.
Use sort! to sort the array itself and modify it.
Provide a block to sort for custom sorting rules.
Sorting strings is case-sensitive by default; use downcase for case-insensitive sorting.
Remember sort returns a new array, so assign it if you want to keep the sorted result.