Random number from a range?
Posted by Nicholas Mon, 18 Dec 2006 02:31:00 GMT
As an old PHP hat I’ve missed the ability of being able to grab a random number out of a range ala PHP’s sweet rand() function. Sure it’s easy to create an alternative, but it’s just not as convenient. Today a friend of mine had a need to do just that. However there was a catch: He needed to pull a random number from a range, yet ignore a variable amount of numbers from that range.
The solution I came up with, which I figured may be of some use to somebody, was this:
class Range
def random( *ignore )
numbers = [ *self ]
numbers -= ignore
numbers[ rand( numbers.size ) ]
end
end
I figured adding this to the Range class made the most sense, though I suppose that’s debatable.
This was the simplest approach to solving this problem that I could think of, though I’d be eager to learn of an even more elegant way.
I’ve also noticed, while adding this, that some of my previous articles are suffering from the dreaded comment spam. I feel I’m going to have to hack Typo to stop some of this madness. I’ll post my solution when I actually make one.