What is sort!() in Ruby?
In Ruby, we can sort an array using the functions sort!() or sort(). The return value after any of these functions are executed is a sorted version of the original array.
The difference is that unlike sort(), the sort!() method changes the original array to the sorted one.
Let’s take a look at how sort!() works.
Syntax
array.sort!()
Parameters
The sort!() method takes no parameters.
Example
In the example below, we create arrays, call the sort!() function, and print the arrays.
# 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!()}"
As we stated earlier, using sort!() changes the original array to the new sorted array.
Take a look at the example below:
# create an arrayarray1 = [5, 2, 4, 1, 3]# print the sorted arraysputs "#{array1} sorted = #{array1.sort!()}"# Now print original arrayputs "#{array1}" # Changes to [1, 2, 3, 4, 5]