From: Michael Neumann Date: 2004-08-10T18:48:53+09:00 Subject: Re: empty? and size in Enumerable Robert Klemme wrote: > "Martin DeMello" schrieb im Newsbeitrag > news:xW%Rc.68814$gE.48438@pd7tw3no... > >>Robert Klemme wrote: >> >>>Hm, sounds to me like it was not general enough to include it in >>>Enumerable. Before I see that method I'd prefer to have size and > > empty? > >>>in Enumerable. Just my 0.02 EUR... >> >>Can empty? be reliably implemented in terms of each for every >>enumerable? I can't think of an obvious problem with it, but that >>doesn't mean there isn't one. > > > Yes, that's possible IMHO. My suggestion would be: > > module Enumerable > # O(1) > def empty? > each { return false } > true > end > > # O(n) > def size > inject(0) {|s,| s+1} > end > end > > Do you see any problems? There's only the little disadvantage that size > is O(n) while there are most likely more efficient implementations for > certain collections. But classes like Array and Hash provide their own > implementation anyway, which then overrides Enumerable#size. So there's > no drawback IMHO, only the advantage that you don't have to write it if > you have a collection that can determine its size only via a complete > iteration. Hehe, and how long does it take to determine the size of infinite or cyclic Enumerable's? ;-) require 'enumerator' to_enum(:loop).each { ... break if ... } to_enum(:loop).size # ??? Regards, Michael