Skip to content

Instantly share code, notes, and snippets.

@skuroki
Created June 2, 2012 06:59
Show Gist options
  • Save skuroki/2857051 to your computer and use it in GitHub Desktop.
Save skuroki/2857051 to your computer and use it in GitHub Desktop.
Think about stable sort in ruby(1.9.3)
[10] pry(main)> [[10, 120], [20, 190], [10, 110], [20, 220], [10, 130], [20, 180]].sort_by(&:first)
=> [[10, 120], [10, 130], [10, 110], [20, 220], [20, 190], [20, 180]]
[12] pry(main)> [[10, 120], [20, 190], [10, 110], [20, 220], [10, 130], [20, 180]].each.with_index.sort_by { |a, i| [a.first, i] }
=> [[[10, 120], 0],
[[10, 110], 2],
[[10, 130], 4],
[[20, 190], 1],
[[20, 220], 3],
[[20, 180], 5]]
[13] pry(main)> [[10, 120], [20, 190], [10, 110], [20, 220], [10, 130], [20, 180]].each.with_index.sort_by { |a, i| [a.first, i] }.map(&:first)
=> [[10, 120], [10, 110], [10, 130], [20, 190], [20, 220], [20, 180]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment