From: Austin Ziegler Date: 2002-07-10T02:18:11+09:00 Subject: Re: for ... else ... end On Wed, 10 Jul 2002 01:52:38 +0900, David Alan Black wrote: > I still don't see how a code block can have an 'else' clause. > Wouldn't this make for some awfully bizarre code? I can't, either -- which is why I'm asking the questions: 1. How would this work in a case where there is no loop, but just a block? 2. How would I construct my own each member function to take advantage of the else (and possibly other clauses)? I can see the utility of the construct, but I think it makes a lot more sense in languages where there are real control structures. > array.each {|e| else puts "Empty array"} > Given an empty array, this else clause would execute. [...] And, > come to think of it.... shouldn't the block not be entered at all > if the array is empty? What the "else" thing means is that the > block *will* be entered. I wish I knew the technical term for why > that isn't OK :-) but doesn't it feel very non-OK? Agreed. I'd prefer to do that as: puts "Empty array" if array.empty? array.each { |e| puts e } unless array.empty? It might be nice to have some syntactic sugar that does something like that: array.each { |e| puts e } unless array.empty then puts "Empty array" (Not currently possible, AFAIK, and probably really nasty in the interpretation of same.) Why not something like: case array.each { |e| puts e } when array.empty? puts "Empty array" when broken # The ugly part puts "Broke from each early" else puts "Done processing" end I don't know if that will work (except, of course, 'broken', which won't work), but it seems to be conceptually cleaner. IMO. > It seems to me to be crossing all sorts of borders and boundaries > for a proc/block to have this kind of knowledge. Is a block of > code really supposed to know whether or not it was executed, > without any explicit test? I think that it's a bad idea, myself. > I guess this thread is bringing out my Ruby-conservative streak :-) > I'm personally very happy to do something like this (which I know > isn't identical to your example, but still): FWIW, this was someone else's example that I adapted from a for...end format to an each do...end format -- because I don't think that it's necessarily a good way of doing it. -austin -- Austin Ziegler, austin@halostatue.ca on 2002.07.09 at 13.06.12