Skip to content

Sorting an Array Alphabetically with Ruby

Ruby, Array, Sorting1 min read

When working with arrays in Ruby, there are times when you might need to sort the elements alphabetically. Whether it's sorting a list of names or organizing strings, Ruby provides several ways to achieve this. In this post, we'll delve into the different methods available for sorting an array alphabetically in Ruby, along with code examples to illustrate each approach.

Using the sort Method

The most straightforward way to sort an array alphabetically in Ruby is by utilizing the sort method. This method returns a new array sorted in ascending order.

1names = ["Alice", "Charlie", "Bob"]
2sorted_names = names.sort
3puts sorted_names

In this example, the array names containing three strings is sorted alphabetically using the sort method.

Sorting in Reverse Order

If you need to sort the array in reverse alphabetical order, Ruby provides the sort method with a block that allows you to modify the sorting behavior.

1names = ["Alice", "Charlie", "Bob"]
2reverse_sorted_names = names.sort { |a, b| b <=> a }
3puts reverse_sorted_names

By specifying the block { |a, b| b <=> a }, the elements in the array are sorted in reverse order.

Using sort_by with Block

Another powerful method for sorting an array alphabetically in Ruby is through the sort_by method. This method allows you to specify a block to define the sorting criteria based on a specific attribute or condition.

1fruits = ["apple", "banana", "cherry"]
2sorted_fruits_length = fruits.sort_by { |fruit| fruit.length }
3puts sorted_fruits_length

In this example, the sort_by method sorts the array fruits based on the length of each string, resulting in a sorted array based on string length.

Sorting with sort_by and String Methods

You can also combine the sort_by method with string methods to perform more complex sorting operations. For instance, sorting an array of words based on their last character can be accomplished as follows:

1words = ["ruby", "array", "sorting", "alphabetically"]
2sorted_words_last_char = words.sort_by { |word| word[-1] }
3puts sorted_words_last_char

By using the sort_by method along with string manipulation (in this case, extracting the last character of each word), the array is sorted based on the defined criteria.