Ruby’s sorting is not stable!

Gabriel Sobrinho14 Sep 2023

While investigating a flaky test in a Code1 customer, we found an issue where an array was being sorted wrongly, apparently randomly, while working fine locally.

After a few rounds of investigation, we found a vital saying in Ruby’s documentation: The result is not guaranteed to be stable. When two keys are equal, the order of the corresponding elements is unpredictable.

Stable sorting keeps the elements in the same order if considered equal, while unstable sorting doesn’t.

While in the first sort, you see objects in the wrong order, in the second sort, they are always in the correct order.

Print sort

That’s about performance since stable sorting is much much slower than unstable sorting, as you can see here:

But since our collection doesn’t have more than a hundred objects in general, it wasn’t a big deal.

Done! We fixed an issue that lasted more than a year!

Subscribe to receive our posts first hand!

Code1 logo