so surprised syntax error not caught here

  • Thread starter SpringFlowers AutumnMoon
  • Start date
S

SpringFlowers AutumnMoon

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"
 
A

Austin Ziegler

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)

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
 
P

Phlip

SpringFlowers said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top