What is array.sort() in Ruby?

In Ruby, it is easy to sort an array with the sort() function. When called on an array, the sort() function returns a new array that is the sorted version of the original one.

Syntax

array.sort()

Parameter

The sort() function takes no parameter. It is only called on an array.

Return value

The value returned is a new array that is sorted from the original one.

Code

In the example below, we created arrays and we called the sort() function on them. Then, the value returned is printed to the console.

# create arrays
array1 = ["e", "d", "a", "b", "c"]
array2 = [5, 2, 4, 1, 3]
array3 = ["Ruby", "JavaScript", "Java", "Python"]
# print the sorted arrays
puts "#{array1} sorted = #{array1.sort()}"
puts "#{array2} sorted = #{array2.sort()}"
puts "#{array3} sorted = #{array3.sort()}"

Sorting an array of elements that are neither strings or numbers will throw an error.

Arrays that are neither strings or numbers can not be sorted, hence an error will be thrown. See the example below.

# create arrays
array4 = [true, false]
array5 = [nil, "", 1, 0]
# printing the value will throw an error
puts "#{array4} sorted = #{array4.sort()}"
puts "#{array5} sorted = #{array5.sort()}"

Free Resources