How to Use the Ruby sort_by Method

09/22/2021

Contents

In this article, you will learn how to use the Ruby sort_by method.

Using the sort_by method

The Ruby sort_by method is a useful method for sorting an array of elements based on a specific attribute or property of each element. It takes a block of code that returns the value to be used for sorting, and returns a new array with the elements sorted based on that value.

Here is an example of how to use the sort_by method in Ruby:

# Define an array of hashes with name and age properties
people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 }
]

# Sort the people array by age using sort_by
people_sorted_by_age = people.sort_by { |person| person[:age] }

# Print the sorted array
puts people_sorted_by_age.inspect

In this example, we define an array of hashes with name and age properties. We then use the sort_by method to sort the people array by the age property of each hash. The block of code passed to sort_by returns the value of the age property for each element, so the people array is sorted based on age.

The resulting people_sorted_by_age array is a new array with the elements sorted based on the age property, from youngest to oldest. We then print the sorted array using the inspect method to display it on the console.

The sort_by method can also be used to sort elements based on a computed value, rather than just a single property. For example, we could sort an array of strings based on the length of each string:

# Define an array of strings
words = ["apple", "banana", "cherry", "date", "elderberry"]

# Sort the words array by length using sort_by
words_sorted_by_length = words.sort_by { |word| word.length }

# Print the sorted array
puts words_sorted_by_length.inspect

In this example, we define an array of strings and use the sort_by method to sort the array based on the length of each string. The block of code passed to sort_by returns the length of each string, so the words array is sorted based on string length.

The resulting words_sorted_by_length array is a new array with the strings sorted based on length, from shortest to longest.