0

Here's a small ruby script:

p "ruby #{ RUBY_VERSION }p#{ RUBY_PATCHLEVEL }"
p 100.times.collect{|i| i}.sort_by{|j| j % 1}

I would have expect the same result from a version to another. In my case, it's not. Here's the results

"ruby 2.2.3p173"
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

"ruby 2.3.1p112"
[99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 0]

Is that normal?

Luka Kerr
  • 4,161
  • 7
  • 39
  • 50
Rick
  • 3
  • 1
  • You could have simply done `.sort_by { 0 }`. Passing `j` into the block and using it in an operation that always produces `0` has no affect on the sorting . – user229044 May 24 '16 at 15:45

2 Answers2

2

Ruby doesn't guarantee you a sort order if the items are the same.

As to why the result changed between versions, this looks like a relevant change: ruby 2.3 tries to use a c-standard library provided implementation of quicksort in more cases than before.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
1

Have a look at Is sort in Ruby stable?. The quick answer is no, it's not. What this means is that if two values are equivalent, in your case always equal to 0, you can't make any assumptions about where they go in relation to one another.

Community
  • 1
  • 1
Paul Rubel
  • 26,632
  • 7
  • 60
  • 80