From: ahoward Date: 2003-02-12T02:59:31+09:00 Subject: Re: Range#length?!?!? On Wed, 12 Feb 2003, Gavin Sinclair wrote: > On Wednesday, February 12, 2003, 2:44:34 AM, Chris wrote: > > > What happened to Range#length and Range#size? > > They disappeared, amidst some discussion in this group, a little while > ago. A search of the archives should help. > > The reason was that a range of floats has infinite "length" > (conceptually, not literally), and a range of strings has an > expensive-to-calculate length. So the method doesn't make sense in > general. IMHO this makes _perfect_ sense : class Range def size case first when String a = i = 0 first.reverse.each_byte do |byte| a += byte * (256 ** i) and i += 1 end b = i = 0 last.reverse.each_byte do |byte| b += byte * (256 ** i) and i += 1 end return b - a + (exclude_end? ? 0 : 1) when Float return 1.0/0.0 end end end p ('a' .. 'a').size # => 1 p ('a' ... 'a').size # => 0 p ('a' .. 'z').size # => 26 p ('a' ... 'z').size # => 25 p ('aa' ... 'aa').size # => 0 p ('aa' .. 'ab').size # => 2 p ('aa' ... 'ab').size # => 1 p ('aa' ... 'zz').size # => 6425 p (0.0 ... 42.0).size # => Infinity this length of a String Range is easily calculated by interpreting a string as a base 256 number, eg: 'abc' -> 'a'[0] * (256 ** 2) + 'b'[0] * (256 ** 1) + 'c'[0] * (256 ** 0) which makes it very inexpesive (and entirely accurate) to calculate especially since the 'normal' String ranges are made up of quite short strings. p ('even this' ... 'works quickly').size # => 9462642498376336060692356596486 it also seems to make perfect sense for Float Ranges to have size Infinity? this would suprise no one. -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ahoward@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 ====================================