From: "Christoffer Lernö" Date: 2007-02-27T22:13:29+09:00 Subject: Re: generating negative random numbers On Jan 30, 2007, at 08:52 , Martin DeMello wrote: > On 1/30/07, Josselin wrote: >> I know how to generate positive random numbers, but is it possible to >> generate a random number in a range such [-9..+9] ? >> tfyh > > class Range > def rand > Kernel::rand(last - first + 1) + first > end > end > > (-9..9).rand (-9...10).rand won't give the expected answer. I think the below should fix the problem when the last entry in the range is excluded: class Range def rand return first if exclude_end? && last == first Kernel::rand(last - first + (exclude_end? ? 0 : 1)) + first end end