3 ms·
You're right that `sort{rand}` is a bad idea, but not because it could run forever. `rand` in Ruby just returns a number like 0.9307038377384, used in sorting t
by thenduks 18y ago
You're right that `sort{rand}` is a bad idea, but not because it could run forever. `rand` in Ruby just returns a number like 0.9307038377384, used in sorting this will just always sort the same way (since it's always > 0). So Ruby will use the result of `rand` to determine if one element should be sorted before or after another. So maybe a better solution would be to use `sort{rand - 0.5}` or something, so that it will randomly be either < or > 0.
I was curious so I looked Array#rand in the Active Support source code[1], the implementation uses the following code to get a random element:
def rand
self[Kernel.rand(length)]
end
So, this is much better than sorting the whole array in random order and pulling one off the top :) But it still uses `rand`.
[1] http://github.com/rails/rails/tree/e56b3e4c0b60b2b86f5ca9c5e5a0b22fa34d37ab/activesupport http://github.com/rails/rails/tree/e56b3e4c0b60b2b86f5ca9c5e...