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
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