Time for Examples
Here are some examples of Ruby Sort_by method:
Example 1: Let us sort some Coding ninjas resources based on their length.
resourcesCN = ['codingNinjas', 'Interview', 'codingNinjasStudio', 'Library']
sorted_array = resourcesCN.sort_by { |resource| resource.length }
puts sorted_array

You can also try this code with Online Ruby Compiler
Run Code
Output
Library
Interview
codingNinjas
codingNinjasStudio

You can also try this code with Online Ruby Compiler
Run Code
Explanation
We organized the array so that the shorter words appeared at the start of the array by using the sort_by method along with a block of code that calculates each element’s length.
Library has length = 7, hence it came first and so on.
Example 2: Sort in Reverse Order.
We have seen in the above example of how we can add the attribute and sort the array. But, what about the case when we want the array to be sorted in descending order?
In this example we will see how to sort an array in reverse order:
We can use the - operator together with the attribute to sort an array in the opposite direction.
resourcesCN = ['codingNinjas', 'Interview', 'codingNinjasStudio', 'Library']
sorted_array = resourcesCN.sort_by { |resource| - resource.length }
puts sorted_array

You can also try this code with Online Ruby Compiler
Run Code
Output
codingNinjasStudio
codingNinjas
Interview
Library

You can also try this code with Online Ruby Compiler
Run Code
Example 3: Sort an array of hashes by a specific key.
In this example, we will sort the array of hashes with a specific key. Here, we will take the data of Ninjas and sort them by their age.
ninjas = [
{ name: "Alisha", age: 18 },
{ name: "Mehak", age: 20 },
{ name: "Akash", age: 17 }
]
sorted_Ninjas = ninjas.sort_by { |ninja| ninja[:age] }
puts sorted_Ninjas

You can also try this code with Online Ruby Compiler
Run Code
Output
{:name=>"Akash", :age=>17}
{:name=>"Alisha", :age=>18}
{:name=>"Mehak", :age=>20}

You can also try this code with Online Ruby Compiler
Run Code
There are some more examples you can try out on your own for better understanding.
Let us now move to understanding the working of Ruby Sort_by method:
Working of Ruby Sort_by Method
The sort_by method in Ruby uses a sorting algorithm called "TimSort."
-
TimSort is a hybrid sorting algorithm that combines elements of merge sort and insertion sort.
-
TimSort works by dividing the array into smaller chunks, known as "runs," and then merges these runs in a sorted manner.
-
It aims to take advantage of any existing order or partial order in the data, which can make the sorting process more efficient.
-
The algorithm compares the elements based on the key or attribute specified in the block provided to the sort_by method.
-
It uses this comparison to determine the order in which the elements should be sorted.
- By utilizing TimSort, Ruby's sort_by method achieves efficient and stable sorting of elements in an array while also considering the specified attribute or key for sorting.
Frequently Asked Questions
What is the difference between the sort and sort_by method in Ruby?
The sort method sorts elements based on natural order or a custom block, while sort_by sorts elements based on a specific attribute/key defined in a block.
What is the advantage of the sort_by ruby method?
The sort_by method simplifies the sorting process by handling the sorting logic for you. It eliminates the need for writing complex comparison logic or custom sorting algorithms.
What is - operator in Ruby?
In Ruby, the - operator is used as the subtraction or negation operator, depending on the context in which it is used.
Conclusion
In this article, we have discussed Ruby Sort_by method in detail. We have seen various examples of sort_by method to sort the array.
After reading about Ruby Sort_by method, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see Object Marshalling in Ruby, Tainting Objects in Ruby, and Object References in Ruby.
Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.
Feel free to upvote and share this article if it has been useful for you.