From: David Alan Black Date: 2002-07-10T02:36:18+09:00 Subject: Re: for ... else ... end Hi -- On Wed, 10 Jul 2002, Austin Ziegler wrote: > 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? [...] > > 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" Hmmm... unless I'm missing something, this can be done very simply: if array.empty? puts "Empty array" else array.each {|e| puts e} end or even: puts "Empty array" if array.each {|e| puts e}.empty? since Array#each returns the original array. (But that has a slightly inside-out feel to it.) (Of course if it's really just #puts, then: puts if array.empty? then "Empty array" else array end (or ternary operator equivalent, as I think Det pointed out) but that can't be generalized :-) > 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. Sorry if I was attributing too much to you... it was actually hard to find exactly the right point of entry into the thread! David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav