Say I have a class called Person, and it contains things such as last name, first name, address, etc.
I also have a hash table of Person objects that needs to be sorted by last and first name.
I understand that a sort_by will not change the hash permanently, which is fine, I only need to print in that order. Currently, I am trying to sort/print in place using:
@hash.sort_by {|a,b| a <=> b}.each { |person| puts person.last}
I have overloaded the <=> operator to sort by last/first, but nothing appears to actually sort. The puts there simply outputs in the hash’s original order. I have spent a good 4 days trying to figure this out (it is a school assignment, and my first Ruby program). Any ideas? I am sure this is easy, but I am having the hardest time bringing my brain out of the C++ way of thinking.
You appear to be confusing
sortandsort_bysortyields two objects from the collection to the block and expects you to return a <=> like value: -1,0 or 1 depending on whether the arguments are equal, ascending or descending, for exampleSorts the strings by length. This is the form to use if you want to use your <=> operator
sort_byyields one object from the collection at a time and expects you to return what you want to sort by – you shouldn’t be doing any comparison here. Ruby then uses <=> on these objecfs to sort your collection. The previous example can e rewritten asThis is also known as a schwartzian transform
In your case the collection is a hash so things are slightly more complicated: the values that are passed into the block are arrays that contain key/value pairs, so you’ll need to extract the person object from that pair. You could also just work on @hash.keys or @hash.values (depending on whether the person objects are keys or values)