DEV Community

John Leavell
John Leavell

Posted on

1

Ruby .sort and .sort! What's the difference??

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)
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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!

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video 📺

Top comments (1)

Collapse
 
heratyian profile image
Ian •

Great explanation 👍

đź‘‹ Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay