Hello friends,
Today I learned something interesting and helpful. If you didn't know, in Ruby there are Mutating and Non-Mutating Methods. Today, let's focus on the .sort
and .sort!
methods
Mutating Method .sort!
As you might expect, changes the value of an object. When used on an array it sorts the elements in place, directly modifying the original array without creating a new one
# Mutating .sort! method
fruits = ['banana', 'apple', 'orange', 'mango']
fruits.sort!
puts fruits # ['apple', 'banana', 'mango', 'orange'] (sorted in place)
Notice how the original fruits
array is now sorted alphabetically in place without the need for creating a new array.
Non-Mutating Method .sort
As you might expect, does not change the value of an object. When applied to an array, it returns a new array with the elements in ascending order, without modifying the original array. This ensures that the original order of elements remains unchanged.
# Non-Mutating .sort method
numbers = [5,2,8,3,1,7]
sorted_numbers = numbers.sort
puts sorted_numbers # [1,2,3,5,7,8
puts numbers # [5,2,8,3,1,7]
Knowing when to use .sort
and .sort!
is essential. Use .sort
when you want a new sorted array while preserving the original array's order. Choose .sort!
when you want to directly modify the original array.
Remember, using the correct method can make your code more efficient and maintainable.
I hope this helps!
Top comments (1)
Great explanation đź‘Ť