Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Easy

Ruby Sort_by Method

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Do you remember your school days? We used to stand on the ground for exercise during morning assembly. Our teachers used to arrange us based on our height. 

Have you ever thought about how important Sorting is in the programming world?

Sorting is almost applicable everywhere you see. Even the contact list in your phone is sorted, which entails that you can easily access your contact from your phone since the data is arranged in that manner for you.

Ruby Sort_by Method

Today we are going to discuss one of the most famous method of Ruby: Sort_by method. We will be looking at the syntax, implementation and working of Sort_by method with various examples. 

So, let us start: 

Introduction to Ruby Sort_by Method

The sort_by method is a built-in feature of Ruby that allows you to sort elements in an array according to a certain attribute or a key. This key or attribute is defined within a special code block that you provide to the sort_by method.

Imagine you have a bunch of items, like fruits, and you want to sort them based on their size. With the sort_by method, you can easily do that. You just need to tell Ruby which attribute to consider for sorting, in this case, the size of the fruits.

Introduction to Ruby Sort_by Method
  • It simplifies the process of sorting by automatically handling the sorting logic for you.
     
  • It takes a block of code that defines the criteria for sorting and returns a new array with the sorted elements.


Let us now look at its syntax and return value: 

Syntax

array.sort_by { |element| block }

Where, 

  • array: This represents the array you want to sort.
     
  • sort_by: This is the method call that indicates you want to sort the array using a specific attribute.
     

Parameters: 

  • element: This is a placeholder variable that represents each element of the array during the sorting process. You can choose any valid variable name here.
     
  • block: This is a code block that defines the attribute for sorting. Within the block, you specify the key or attribute that determines the sorting order for each element.

Return Value 

The sort_by method returns the new sorted array depending on the specified condition. 

Let us now see some examples to understand the sort_by method better:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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


Output

Library
Interview
codingNinjas
codingNinjasStudio


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


Output

codingNinjasStudio
codingNinjas
Interview
Library

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


Output

{:name=>"Akash", :age=>17}
{:name=>"Alisha", :age=>18}
{:name=>"Mehak", :age=>20}


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 RubyTainting Objects in Ruby, and Object References in Ruby.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem 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.

Previous article
Methods in Ruby
Next article
Assignment in Ruby
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass