How to sort an array of classes that contain nested classes using custom comparison logic in Ruby

1 Answer

0 votes
# A nested class representing an address
class Address
  attr_accessor :city, :zip

  def initialize(city, zip)
    @city = city
    @zip = zip
  end
end

# A class representing a person, containing a nested Address
class Person
  attr_accessor :name, :age, :address

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

# Helper function to print the list
def print_persons(people)
  people.each do |p|
    puts "#{p.name} | age: #{p.age} | city: #{p.address.city} | zip: #{p.address.zip}"
  end
end

# Sort persons by city, then zip, then age
def sort_persons(people)
  people.sort_by! { |p| [p.address.city, p.address.zip, p.age] }
end

# Sample data
people = [
  Person.new("Alice", 30, Address.new("San Francisco", 42100)),
  Person.new("Bob",   40, Address.new("Austin",        32000)),
  Person.new("Carol", 35, Address.new("New York City", 42000)),
  Person.new("Dave",  25, Address.new("Austin",        32000)),
  Person.new("Eve",   28, Address.new("New York City", 61000))
]

# Perform sorting
sort_persons(people)

# Display sorted results
print_persons(people)


=begin
run:

Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100

=end

 



answered Sep 2 by avibootz

Related questions

...