Alle mercoledì 7 marzo 2007, Robert D. ha scritto:
if true then
whatever
elseif
end
now elsif is seen as an undefined method but
Not always. In Robert’s first example,
if true then
whatever
elseif
end
you’ll get a NameError (undefined local variable or method `elseif’ for
main:Object (NameError))
In the following example, instead, you get a syntax error:
if x < 0 then puts “x<0”
elseif x < 3 then puts “0<=x<3”
else puts “x>=3”
end
The error message is:
syntax error, unexpected kTHEN, expecting kEND
elseif x < 3 then puts “0<=x<3”
^
Here, ruby doesn’t complain because elseif doesn’t exist, but because it
finds
a ‘then’ where it shouldn’t be (not following an if or elsif clause). By
the
way, being a syntax error (it when the interpreter is parsing the file,
not
when it executes it), this error is reported whatever the value of x is
(and
even if x doesn’t exist).
All these error messages aren’t very easy to understand for a novice. To
make
a comparison with other programming languages, I tried compiling a C
program
with a similar mistake (in this case writing ‘elseif’ instead of ‘else
if’).
The program was:
int main(){
int a=3;
int b=0;
if( a==4){ b=1;}
elseif(a==2){ b=2;} //should be else if
else{ b=3;}}
}
Compiling with gcc, the error message I got is:
test.c: In function ‘main’:
test.c:5: error: expected ‘;’ before ‘{’ token
As you can see, the error message doesn’t speak of invalid keywords,
but just
of a missing ;
Stefano