Sorting Techniques in Ruby

Lesson Introduction and Overview

Hello, and welcome back! Our journey today takes us into the sorting universe in Ruby. We will learn and utilize Ruby's powerful sorting methods: sort and sort_by. These tools in Ruby significantly simplify the task of sorting. Let's get started!

Understanding Sorting and Its Importance

Sorting refers to arranging data in a specific order, which enhances the efficiency of search or merge operations on data. In real life, we sort books alphabetically or clothes by size. Similar concepts are applicable in programming, where sorting large lists of data for more effective analysis is a frequent practice.

Ruby offers built-in sorting methods: sort for arrays and other enumerables, and sort_by for more complex sorting logic. Here's a demonstration of how we use these methods:

Sorting of Primitive Types and Objects

Sorting with sort makes sorting arrays of primitives a breeze. Let's see it in action!

Sorting Arrays of Primitives

Ruby
arr = [4, 1, 3, 2]
sorted_arr = arr.sort
puts sorted_arr.join(", ") # Output: 1, 2, 3, 4

Sorting Lists of Objects

Ruby
inventory = ["Bananas", "Pears", "Apples", "Dates"]
sorted_inventory = inventory.sort
sorted_inventory.each do |item|
  puts item
end

# Output:
# Apples
# Bananas
# Dates
# Pears

As you can see, sorting in Ruby is as simple as that!

More Complex Sorting Problem

Ruby allows us to define custom sorting logic using blocks. Let's sort a list of students by their grades, with alphabetical sorting applied in the event of ties in grades. First, let's define the Student class:

Ruby
class Student
  attr_reader :name, :grade

  def initialize(name, grade)
    @name = name
    @grade = grade
  end

  def to_s
    "#{name}:#{grade}"
  end
end

Custom Sorting with Block Syntax

Here's how we perform custom sorting using Ruby's block syntax:

Ruby
students = [
  Student.new("Alice", 85),
  Student.new("Bob", 90),
  Student.new("Charlie", 90)
]

sorted_students = students.sort do |s1, s2|
  grade_comparison = s2.grade <=> s1.grade
  grade_comparison == 0 ? s1.name <=> s2.name : grade_comparison
end

puts sorted_students.join(", ") # Output: Bob:90, Charlie:90, Alice:85

In the example above, we create an array of Student objects and sort it using a custom comparison defined via a block. The block first compares Student objects based on their grades in descending order and, in the event of a tie, compares their names in alphabetical order. The <=> operator returns an integer that indicates the relative order of the objects being compared.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal