RCR for Range.rand

B

baumanj

There's already an RCR that advocates the addition of clamp, modulo and
rand methods to the Range class:

http://www.rcrchive.net/rcr/show/270

I'd like to see rand, but I don't so much care about the other two.
Additionally, I have a pretty different idea for the implementation.
So, I have two questions:

1. Sholud I submit my own RCR, or just add my thoughts as a comment to
this one?
2. Any thoughts about my implementation?

class Range
def rand
if endpoints_respond_to?:)succ) && endpoints_respond_to?:)-)
# Things that are discrete, but we don't need to enumerate
explicitly such as Integer, Date, Time
max = exclude_end? ? self.end : self.end.succ
self.begin + Kernel.rand(max - self.begin)
elsif endpoints_respond_to?:)succ)
# Things that are discrete but must be enuerated explicitly such as
String
array = to_a
array.at(Kernel.rand(array.size))
elsif endpoints_respond_to?:)to_f)
# Non-discrete values such as all the numerics
f_begin = self.begin.to_f
f_end = self.end.to_f
size = (exclude_end? ? f_end - Float::EPSILON : f_end) - f_begin
f_begin + size * Kernel.rand
else
raise TypeError.new("can't iterate from #{self.begin.class}")
end
end

# should this be private?
def endpoints_respond_to?(symbol, include_private = false)
self.begin.respond_to?(symbol, include_private) &&
self.end.respond_to?(symbol, include_private)
end
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top