From: Rob Biedenharn Date: 2008-06-11T01:25:12+09:00 Subject: Re: Random Number Stuff On Jun 10, 2008, at 10:13 AM, Dave Bass wrote: > David Stanislaus wrote: >> How would you create a random number generator thats limited to a >> specific rang? say >> >> 1930 - 1950 > > If you want to do this a lot, you could add your own method to the > builtin Range class: > > class Range > def random > self.begin + rand(self.end - self.begin + 1) > end > end It would be safer to do: class Range def random case self.begin <=> self.end when -1 self.begin + rand(self.end - self.begin + (self.exclude_end? ? 0 : 1)) when 0 self.begin when +1 self.begin - rand(self.begin - self.end + (self.exclude_end? ? 0 : 1)) end end end Since a Range does not require the endpoints to be ordered. And 1930..1950 is different from 1930...1950 according to whether 1950 is to be included. > Then generate random numbers like this: > > puts (1930...1950).random > > (For some reason this gives "warning: (...) interpreted as grouped > expression"; I don't know why. Maybe someone more experienced could > explain.) Because your usage is to group the 1930...1950 so the random method is sent to the Range object and not to the 1950. If you added the parentheses for the puts, the opening parenthesis would no longer be ambiguous: puts((1930...1950).random) tries = Hash.new {|h,k| h[k] = 0 } range = 1930..1950 500.times {|_| tries[range.random] += 1 } tries.sort.each {|year,count| puts "%d %3d"%[year,count] } -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com