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)
Here's my go:
def random(value)
if value.class.method_defined? 'entries'
entries = value.entries
entries[rand(entries.length)]
else
rand(value)
end
end
this works with arrays and hashes too.
I'm coming to Ruby via RoR and i'm loving it, I should be writing a
web app and i'm playing with Ruby instead.
Ben
Ben Stephens <foolfodder@gmail.com> writes:
I was wondering if rand() could support syntax like:
rand(0..100)
That's a great idea!
Here's my go:
def random(value)
if value.class.method_defined? 'entries'
entries = value.entries
entries[rand(entries.length)]
else
rand(value)
end
end
this works with arrays and hashes too.
Oh, I don't know about that... I'd do something like this:
def random(range)
case range
when Integer
rand(range)
when Range
a, b = [range.begin, range.end].sort
if a.integer? and b.integer? then
if range.exclude_end?
then rand(b - a) + a
else rand(b - a + 1) + a end
else
rand * (b - a) + a
end
end
end
I'm coming to Ruby via RoR and i'm loving it, I should be
writing a web app and i'm playing with Ruby instead.
That's the downside of using such a powerful language:
You can never stop playing with it!
···
--
Daniel Brockman <daniel@brockman.se>
So really, we all have to ask ourselves:
Am I waiting for RMS to do this? --TTN.
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
···
On 7/19/05, Ben Stephens <foolfodder@gmail.com> 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)