From: Robert Klemme Date: 2008-05-16T17:48:24+09:00 Subject: Re: Randomizing an Array? 2008/5/15 Joao Silva : > Florian Frank wrote: >> Daniel Waite wrote: >>> Florian Frank wrote: >>>> Don't do this, better use (1..10).sort_by { rand }. Your version is >>>> equivalent to (1..10).sort { 1 } and *always* creates the same >>>> permutation for this array. >>> >>> It's random for me. Both work. >> >> No, really, it isn't. It may "look random", but try sorting (1..10) many >> times and ponder the coincidence. > > That's because sort{ foo } expects foo to be in -1,0,1. I don't think so - the sign is important: irb(main):001:0> (1..10).sort { -1 } => [1, 2, 3, 7, 4, 9, 5, 8, 6, 10] irb(main):002:0> (1..10).sort { 1 } => [10, 6, 1, 7, 3, 8, 5, 9, 4, 2] irb(main):003:0> (1..10).sort { 10 } => [10, 6, 1, 7, 3, 8, 5, 9, 4, 2] irb(main):004:0> (1..10).sort { -10 } => [1, 2, 3, 7, 4, 9, 5, 8, 6, 10] > rand() is always [0, 1). Did you mean [0,1[? > rand(2)-1 is (-1,1) however and thus will work just fine. :) rand(2)-1 is (-1,0). I would rather do rand(3)-1 or rand(2) - 0.5 - But all this is worse than sort_by { rand } IMHO. Kind regards robert -- use.inject do |as, often| as.you_can - without end