Question

How do I stably sort an array? The value I want to sort by can have a lot of duplicates, and I'm not sure which sort algorithm ruby uses. I'm thinking insertion sort would have worked best for me.

Example:

a = [[:a, 0], [:b, 1], [:c, 0], [:d, 0]]
a.sort_by { |x, y| y }  # => [[:a, 0], [:d, 0], [:c, 0], [:b, 1]]

Looking for

[[:a, 0], [:c, 0], [:d, 0], [:b, 1]]
Was it helpful?

Solution

Put the key that you originally wanted to sort by and the index into an array, and sort by that.

a.sort_by.with_index { |(x, y), i| [y, i] }
  # => [[:a, 0], [:c, 0], [:d, 0], [:b, 1]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top