From: ara.t.howard@... Date: 2006-04-14T00:31:03+09:00 Subject: Re: Range#size On Fri, 14 Apr 2006, Jon Bauman wrote: > Jeremy Tregunna wrote: >> On 13-Apr-06, at 9:20 AM, Meinrad Recheis wrote: >> >>> does anyone object to adding the method :size to class Range? >> >> Forgive me for being blunt, but Ranges don't have a fixed size, so >> how could you possibly measure it accurately? Force class >> implementers to implement not only a #succ method for their objects, >> but also a #range_size method which would give a formula for >> calculating the size? I mean seriously... > > You know, it's not as though all range operations work with all range > types anyway: > > $ irb --simple-prompt >>> (1.0..2.0).each {|x| p x } > TypeError: can't iterate from Float > from (irb):1:in `each' > from (irb):1 > > So, what would be wrong with allowing size for object that implement the > - operation and giving an error for those that don't? nothing. but try to write it. it's harder than you might think. you need to define as something like this: class Range def size begin first.distance last rescue NoMethodError begin last.distance first rescue NoMethodError raise NoMethodError, "size" end end end end class Fixnum def distance other (other - self).abs end end class Float def distance other Float::MAX/Float::MIN # Infinity end end in otherwords the endpoints must to the range size checking - otherwise the Range class would need to know about every class and how to calculate sizes for all M x N combinations. if the endpoints calculate it we can easily do (0 .. 1).size or (0.0 .. 1.0).size but what about (0 .. 1.0).size ?? how does Range now which endpoint to use as 'other'? if we use 1.0 it works. if we use 0 it does not. it's easy enough to fix this for only Fixnum and Float using a smart coerce - but then we have to deal with Rational, Bignum, Complex, String, etc. and we haven't even hit user defined types. i'm not saying there isn't an elegant solution. but the problem becomes evident imediately when one trys to solve the problem generically. regards. -a -- be kind whenever possible... it is always possible. - h.h. the 14th dali lama