Created
February 10, 2012 13:05
-
-
Save mpapis/1789571 to your computer and use it in GitHub Desktop.
ruby not preserving order of array elements when sorting
This file contains 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
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