> From: uncutstone wu > Sent: Monday, June 19, 2006 9:54 AM > Subject: Is it more convenient to have a random_each in ruby stdlib? > > I found it may be a common case that we need randomly > enumerate elements > in a array or some other collections. > Please take a look at the very simple snippet of code below: > > class Array > def random_each > a = self.dup > n = len = self.length > len.times do > index = rand(n) > yield a[index] > a.delete_at(index) > n -= 1 > end > end > end > > a = [1,2,3,4,5,6,7] > a.random_each {|e| print e , ' '} > > result: > 7 1 6 2 4 3 5 > > I don't whether it is proper to put this kind of simple but useful > utility in the standard library of ruby. > > Thanks. > > uncutstone I think it's a little bit to simple to be put in the standard lib. a.sort_by{rand}.each {|e| print e , ' '} cheers Simon