From: Robert Klemme Date: 2004-08-10T18:36:15+09:00 Subject: empty? and size in Enumerable (was: Re: FirstEachLast, an extension to the Enumerable module.) "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. Kind regards robert