Skip to content

Instantly share code, notes, and snippets.

@mpapis
Created February 10, 2012 13:05
Show Gist options
  • Save mpapis/1789571 to your computer and use it in GitHub Desktop.
Save mpapis/1789571 to your computer and use it in GitHub Desktop.
ruby not preserving order of array elements when sorting
1.9.3p0 :001 > Z=Struct.new(:n,:v)
=> Z
1.9.3p0 :002 > z=[ Z.new('b',1), Z.new('b',2), Z.new('a',1)]
=> [#<struct Z n="b", v=1>, #<struct Z n="b", v=2>, #<struct Z n="a", v=1>]
1.9.3p0 :003 > z.sort_by{ |z| z.n }
=> [#<struct Z n="a", v=1>, #<struct Z n="b", v=2>, #<struct Z n="b", v=1>]
1.9.3p0 :004 > z.each_with_index.sort_by{ |z, i| [z.n, i] }.map{|z,_| z}
=> [#<struct Z n="a", v=1>, #<struct Z n="b", v=1>, #<struct Z n="b", v=2>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment