From: Rick DeNatale Date: 2007-09-23T04:24:46+09:00 Subject: Re: Idiomatic Ruby for Array#extract / Range#length? On 9/22/07, Olivier Renaud wrote: > Le jeudi 20 septembre 2007 14:28, Sammy Larbi a �crit: > > During the monthly meeting of our code dojo, we were surprised by a couple > > of things in Ruby, so I had a couple of questions I'd like to ask the > > community: > > > > 1) Would it make sense to talk about a Range having a length, as in: > > > > class Range > > def length > > self.end - self.begin > > end > > end > > This code will work only when begin and end respond to #-. This is a valid > implementation for Numeric objects, but not for other classes. > In the general case, you'd have to generate every objects of the range to > count them (using #to_a and #size). I think that it's debatable even in the case of Numerics, for example: (1.2..1.5).length #=> 0.3 Normally length returns the number of elements in a collection, and the method as provided doesn't actually work correctly for integer ranges, it should be: class Range def length 1 + last - first end end But, what about: (1...3).length end-start would give 2 but: (1...3).to_a => [1, 2] To fix this: class Range def length last - first + (exclude_end? ? 0 : 1) end end Now we have another case: (3..1).to_a #=> [] so: class Range def length [0, last - first + (exclude_end? ? 0 : 1)].max end end But then what about: (1.2..1.5).length A collection can't have 0.3 elements! I think it only makes sense for Integer ranges. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/