Created
March 5, 2012 20:28
-
-
Save kaosf/1980887 to your computer and use it in GitHub Desktop.
stable_sort_by (Ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def stable_sort_by | |
n = 0 | |
sort_by { |x| [yield(x), n += 1] } | |
end | |
end | |
p [[83, 'annette'], [82, 'kate'], [82, 'lucy']].sort_by { |x| x[0] } | |
p [[83, 'annette'], [82, 'kate'], [82, 'lucy']].stable_sort_by { |x| x[0] } | |
# p [[83, 'annette'], [82, 'kate'], [82, 'lucy']].stable_sort_by #=> no block given (yield) (LocalJumpError) | |
# ref. http://ideone.com/x3jSc | |
# http://moserei.de/2008/09/18/stable-array-sorting-in-ruby.html | |
# http://d.hatena.ne.jp/troter/20070514/1179073399 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also:
sort_by.with_index { |x, idx| [yield(x), idx] }