From: Jacob Fugal Date: 2005-07-20T00:54:06+09:00 Subject: Re: Regarding rand On 7/19/05, Ben Stephens wrote: > I was reading Learn to Program by Chris Pine yesterday, in one bit it says: > ' Note that I used rand(101) to get back numbers from 0 to 100, and > that rand(1) always gives back 0.' > > I was wondering if rand() could support syntax like: > rand(0..100) An extension I've frequently used is this: module Enumerable def random ary = self.to_a ary[rand(ary.length)] end end This is purposefully naive. It won't work with enumerables that don't terminate (e.g. a sequence generator), but then again, neither will several other methods from Enumerable, such as select, reject, etc. It will work, but is inefficient for large non-array Enumerables such as the range (0..1_000_000) since it has to convert it to a 1_000_000 member array. However, in the most frequent case of a relatively small array of range, it can be quite useful: # random number between 1 and 100 number = (1..100).random # random letter from A to Z letter = ('A'..'Z').random # random primary color color = [ :red, :green, :blue ].random The first two are much more efficient if I calculate the random number, but I think this unification of random selection from an Enumerable is useful. I might possibly write an optimized version for Range eventually... Jacob Fugal