Because arrays are a fundamental object in Ruby and other programming languages, Ruby provides a way to sort elements without writing an excellent custom algorithm.
This guide will teach you how to sort an array by using Ruby’s built-in methods and functionalities.
How to Sort An Array
Ruby provides various ways to sort an array. The sort and sort_by methods in Ruby are some of the most fundamental for sorting an array.
#1: Using the sort method
The sort method is defined in the Enumerable module, and it returns the values of the array sorted.
For example:
print nums.sort
[1, 2, 11, 20, 21, 22, 23, 28, 34, 53, 100]
By default, the method will return the items in the array sorted in ascending order.
It works using the spaceship operator, which returns 1 if a value is greater than, 0 for equal to, and -1 for less than.
If you provide an array of strings, the sorted array will be in alphabetical order as:
print databases.sort
["Elasticsearch", "Memcached,", "MongoDB,", "MySQL,", "PostgreSQL,", "Redis,"]
You can pass a block to the sort function if you want to implement a custom sorting order. For example, the following implements a reverse order using the sort method.
print nums.sort {|x, y| y <=> x}
[100, 53, 34, 28, 23, 22, 21, 20, 11, 2, 1]
Ruby also allows you to sort an array in place using the sort! method. The method will affect the original method into the new sorted array as:
nums.sort!
print nums
[1, 2, 11, 20, 21, 22, 23, 28, 34, 53, 100]
NOTE: Use the sort! method with caution; it overwrites the original array, as shown in the example above.
#2: Sort_by method
The sort_by method provides flexibility when sorting compared to the sort method. Let us look at a few examples to see how sorting using the sort_by method works.
The first example is sorting by the length of a string.
print databases.sort_by {|content| content.length}
["Redis", "MySQL,", "MongoDB,", "Memcached,", "PostgreSQL,", "Elasticsearch"]
Sorting of the elements in the array happens in ascending order based on the string content length.
We use the length property of the string as the sort_by method expects a numerical value.
Suppose we want to sort the string in reverse order using the sort_by method? In such a case, we can add a minus operator in length, as shown below:
print databases.sort_by {|content| -content.length}
The above example will return the sorted array in descending order.
Closing
This guide has shown you how to work with arrays and sort them using built-in Ruby methods.