From: "David A. Black" Date: 2005-05-12T08:19:09+09:00 Subject: Re: object loops and what they return Hi -- On Thu, 12 May 2005, Eric Mahurin wrote: >>> Consider these loops: >>> >>> . { } >>> >>> where loop method is each, each_with_index, upto, downto, >> step, >>> and probably others. >>> >>> Although it is not documented, all of these look to return >> the >>> original object (collection or int). >> >> I think the return values are documented in ri for all of >> these. > > Enumerable says nothing about the return value or each. There's no Enumerable#each; you have to implement it :-) > Array.each says it returns an Array, but not what's in that > Array. Before testing, I was thinking it might be the same as > map/collect. The integer loops also say they return an > integer, but not what it is. I think you're misreading the ri output. For example, in this: enum.each_with_index {|obj, i| block } -> enum 'enum' is a variable or object, and it is both the receiver of the method and the return value. The 'enum' on the right is the same as the 'enum' on the left. That documents the returning-receiver behavior. >>> With "each" returning nil, you can also see that many of >> the >>> derived loops in Enumerable become trival almost to where >> you >>> don't need them. >> >> On the other hand, if you were to do this (looking for nil): >> >> obj = array.each {|e| break(e) if e.nil? } >> >> and each returned nil, you wouldn't know whether you'd >> succeeded or >> not. > > Then you do it another way. Differentiating between the > element nil in a collection and nil meaning nothing is a common > problem, I think. You have the same problem using find: > > obj = array.find{|e| not e.kind_of?Integer } > > If you were looking for the first non-integer in array and it > happened to be nil, you couldn't tell whether nil was that > object or there were no non-integers. That's true -- it's something one has to work around in various places. I guess my feeling is that having each and friends return nil won't cause that not to be the case, and that, given that double checks and so on are sometimes needed, there's already a pretty full tool set for doing them. David -- David A. Black dblack@wobblini.net