Sorting in lexicographical order

ruby, sorting

Solution

First the spaceship operator is `<=>` not `<==>`

Secondly you're not combining the 2 comparisons correctly: the result of the comparison will be -1,0,or 1. These are all truthy values and `true && foo` is just `foo`, so your code would just sort by the y values

You could write this as

x_ordering = a.x <=> b.x
x_ordering == 0 ? a.y <=> b.y : x_ordering

However array already implements `<=>` so you could just do

array.sort! { |a,b| [a.x, a.y] <=> [b.x, b.y]}

Which is a little terser and clearer at expense of creating 2 arrays in each comparison

You could even do

 array.sort_by! { |a| [a.x, a.y] }

Which is even clearer, but with a slightly different memory profile. This creates an array with the original values replaced by the values returned by the block and uses that to sort the original array.

I'd usually use the latter version unless I had a compelling reason to do otherwise.

Problem

So I want to sort my array of coordinates in lexicographical order. But I'm not sure how to do that. Each element in the array is a `Coordinate` object, with `Fixnum` fields `#x` and `#y`. I'm new to Ruby and don't necessarily understand the sort enumeration. Would it be something like this? ``` coordinate_array.sort! { |a,b| a.x <==> b.x && a.y <==> b.y } ```

Original source