So surprised syntax error not caught here

the following syntax error for “elif” is not caught? (should be elsif)

def foo(i)
if i < 0
return “Less than 0”
elif i == 0
return “it is zero”
else
return “Greater than 0”
end
end

p foo(-2)
p foo(0)
p foo(10)

==================
Output:

“Less than 0”
“Greater than 0”
“Greater than 0”

From: [email protected] [mailto:[email protected]] On Behalf
Of
SpringFlowers AutumnMoon
Sent: Tuesday, September 25, 2007 7:50 PM

end
end

Rewrite indents this way to understand:

def foo(i)
if i < 0
return “Less than 0”
elif i == 0
return “it is zero”
else
return “Greater than 0”
end
end

The “problem line” is parsed as

elif(i == 0)

Interpreter doesn’t complain on non-existent “elif” methods, because the
line just never evaluated.

V.

On 9/25/07, SpringFlowers AutumnMoon [email protected] wrote:

end

p foo(-2)
p foo(0)
p foo(10)

It’s treating “elif” as a (possible) method call that’s never reached
because of the “return”. You don’t need “return” for what you have:

def foo(i)
if i < 0
“Less than 0”
elif i.zero? # i == 0
“Equal to 0”
else
“Greater than 0”
end
end

That will fail, but not with a syntax error. (It should fail with an
UnknownMethod.) Ruby is expression-oriented, and the last expression
executed in the execution path is returned from the execution path.

-austin

SpringFlowers AutumnMoon wrote:

the following syntax error for “elif” is not caught? (should be elsif)

def foo(i)
if i < 0
return “Less than 0”
elif i == 0
return “it is zero”

Ruby is interpretive; it does not link all its symbols to real
entities at compile time. (Unlike certain other languages we could
mention.

elif could be a function that takes a boolean. Ruby can’t know this
until it interprets the line, because you might have used eval() or
something to create that function before getting here.

In exchange for a lot more flexibility, Ruby does fewer sanity checks
at parse time.

To keep Ruby on track, and catch errors like this, all Ruby developers
should write unit tests for everything.

Austin Z. wrote:

"Greater than 0"
           * [email protected] * http://www.halostatue.ca/feed/
           * [email protected]

My word, you have just given me a reason to stop using returns !!!

It doesn’t hurt code readability to go by syntax rather then insert the
“Yes
Mr/Miss Programmer don’t forget we return here” return statements
through out
code ether.

TerryP.