Skip to content

Instantly share code, notes, and snippets.

@kaosf
Created March 5, 2012 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaosf/1980887 to your computer and use it in GitHub Desktop.
Save kaosf/1980887 to your computer and use it in GitHub Desktop.
stable_sort_by (Ruby)
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
@tokland
Copy link

tokland commented Jan 30, 2015

Also: sort_by.with_index { |x, idx| [yield(x), idx] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment