Sorting a List of Custom Objects in Ruby by Nested Attributes - Unexpected Sort Order
I need some guidance on I'm working on a personal project and I've searched everywhere and can't find a clear answer... I'm trying to sort an array of custom objects in Ruby based on nested attributes, but the results are not what I expect. I have a class `Person` that looks like this: ```ruby class Person attr_accessor :name, :address def initialize(name, address) @name = name @address = address end end ``` The `address` attribute is itself an object that has properties `city` and `zipcode`. Here's how the `Address` class is structured: ```ruby class Address attr_accessor :city, :zipcode def initialize(city, zipcode) @city = city @zipcode = zipcode end end ``` I create a few `Person` instances like this: ```ruby people = [ Person.new('Alice', Address.new('New York', '10001')), Person.new('Bob', Address.new('Los Angeles', '90001')), Person.new('Charlie', Address.new('New York', '10002')), ] ``` I want to sort this list of people primarily by `address.city` and then by `address.zipcode`. I expected to achieve this sorting using the `sort_by` method: ```ruby sorted_people = people.sort_by { |person| [person.address.city, person.address.zipcode] } ``` However, when I check the sorted result, it appears that `sorted_people` is not in the expected order. Instead of being ordered by city first, the output seems mixed: ```ruby sorted_people.each do |person| puts "#{person.name}: #{person.address.city}, #{person.address.zipcode}" end ``` When I print this, I get: ``` Alice: New York, 10001 Charlie: New York, 10002 Bob: Los Angeles, 90001 ``` It seems like the sort doesn't respect alphabetical order as I expect. Also, I noticed that the `zipcode` values are not being factored into the ordering as a secondary criterion. Am I missing something in my approach, or is there a specific way to ensure that the nested attributes are being sorted correctly in Ruby? I am using Ruby 2.7.0. Any insights would be appreciated! Has anyone else encountered this? For context: I'm using Ruby on Ubuntu. Is there a better approach? I'd really appreciate any guidance on this. I'd really appreciate any guidance on this.