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.
array.sort()
The sort()
function takes no parameter. It is only called on an array.
The value returned is a new array that is sorted from the original one.
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 arraysarray1 = ["e", "d", "a", "b", "c"]array2 = [5, 2, 4, 1, 3]array3 = ["Ruby", "JavaScript", "Java", "Python"]# print the sorted arraysputs "#{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 arraysarray4 = [true, false]array5 = [nil, "", 1, 0]# printing the value will throw an errorputs "#{array4} sorted = #{array4.sort()}"puts "#{array5} sorted = #{array5.sort()}"