The sort() Method is used to sort a Array in Ascending/Descending order.
At first let us see an example to sort a Array in Ascending order.
x = ["Mohan", "Kriti", "Salim"] y = x.sort() puts "The Sorted Array in ascending order is #{y}
So, in the above code we have created a Array and initialised to the variable x.
x = ["Mohan", "Kriti", "Salim"]
Below is how the values are positioned in the Array,
Then we have used the sort() method to sort the Array x in ascending order and assigned the sorted values to a new array y.
y = x.sort()
And the Array x gets sorted with Kriti as the first value, Mohan second and Salim as the third.
And we get the below output.
The Sorted Array in ascending order is ['Kriti', 'Mohan', 'Salim']
just remember, the array x is not changed.
Next let us see, how to sort a Array in Descending order.
x = ["Mohan", "Kriti", "Salim"] y = x.sort().reverse() puts "The Sorted Array in ascending order is #{y}"
So, in the above code we have created a Array and initialised to the variable x.
x = ["Mohan", "Kriti", "Salim"]
Below is how the values are positioned in the Array,
Then we have used the reverse() method along with the sort() method.
So, the sort() method sorts the values in ascending order. Then we use the reverse() method to reverse the array items.
And the array is sorted in descending order.
y = x.sort().reverse()
And assign the new array to y.
And the Array x gets the elements in descending order with Salim as the first value, Mohan second and Kriti as the third.
And we get the below output.
The Sorted Array in descending order is ['Salim', 'Mohan', 'Kriti']
Even here the sort() Method is used to sort a Array with numbers in Increasing/Deceasing Order.
At first let us see an example to sort a Array with numbers in Increasing order.
x = [5, 3, 2, 4] y = x.sort() puts "The Sorted Array in increasing order is #{y}"
So, in the above code we have created a Array and initialised to the variable x.
x = [5, 3, 2, 4]
Below is how the values are positioned in the Array,
Then we have used the sort() method to sort the Array x in increasing order. And assign the new sorted array to y.
y = x.sort()
And the numbers in the Array y is sorted.
And we get the below output.
The Sorted Array in increasing order is [2, 3, 4, 5]