Handling Sorted Sets and Custom Comparators in Ruby

Topic Overview

Welcome to our exploration of handling sorted structures using Ruby. In this lesson, we'll learn about alternative methods to manage sorted collections in Ruby. We'll explore how the SortedSet class and Ruby's built-in sorting techniques can help maintain organized data structures.

Intro to Sorted Collections

In Ruby, a SortedSet, available through the set library, is a collection that automatically maintains its elements in a sorted order based on natural ordering or a custom comparator if defined. It is a collection of unique values. In contrast, a Hash is a key-value pair structure that maintains the order of insertion, preserving the sequence in which the pairs are added, but does not sort its keys or values.

Ruby
require 'set'

sorted_set = SortedSet.new(['b', 'a', 'c'])
puts sorted_set.to_a  # Outputs: ["a", "b", "c"]

Introduction to Custom Classes in Ruby

Ruby allows us to define custom classes to create objects that represent our data. For example, you might use a "Person" class to handle employee information or a "Book" class for a library database. Here's a simple implementation of a Person class in Ruby:

Ruby
class Person
  attr_accessor :name, :age

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

person = Person.new("John Doe", 30)
puts person.name  # Outputs: John Doe
puts person.age   # Outputs: 30

Using Custom Classes in Organized Collections

We can manage sorted collections by sorting arrays of custom objects or using SortedSet. Below is an example of how to handle custom sorting of custom objects in Ruby:

Ruby
require 'set'

class Person
  attr_accessor :name, :age

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

  def <=>(other)
    [@age, @name] <=> [other.age, other.name]
  end
end

people = SortedSet.new
john = Person.new("John", 30)
alice = Person.new("Alice", 25)

people.add(john)
people.add(alice)

people.each do |person|
  puts "#{person.name}, Age: #{person.age}"
end
# Output:
# Alice, Age: 25
# John, Age: 30

Comparators and Their Role in Ruby

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