[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: rand random. You've got to be kidding

Gavin Kistner

11/28/2006 8:00:00 PM

From: Smgspices@aol.com [mailto:Smgspices@aol.com]
> I was running the following in SciTE
[snip]
> def shuffle!
> @deck = @deck.sort{rand}
> p @deck
> end
[snip]
> Every time I press F5 I get exactly the same result:

There's your problem. You're using the wrong function.

a = (1..10).to_a
puts "Using sort:"
5.times{ p a.sort{ rand } }

puts ' ', "Using sort_by:"
5.times{ p a.sort_by{ rand } }

#=> Using sort:
#=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
#=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
#=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
#=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
#=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]

Using sort_by:
#=> [7, 8, 9, 2, 6, 5, 10, 3, 4, 1]
#=> [10, 8, 9, 1, 2, 3, 5, 7, 6, 4]
#=> [3, 1, 10, 6, 5, 7, 2, 4, 8, 9]
#=> [9, 5, 1, 6, 7, 3, 8, 4, 10, 2]
#=> [9, 7, 5, 3, 6, 2, 8, 4, 10, 1]