Ruby gotcha: using elsif instead of else if
These past few days I've been playing with Ruby and Rails. I'm really loving the experience so far, but every now and then I stumble upon something that doesn't work as I expected it to.
Last night I encountered problems with one of the most fundamental expressions, namely a if-then-else construct. The interpreter kept complaining that it expected the end keyword, but did not find it.
My code was similar to the sample code below:
if 2 == 3
puts "foo"
else if 3 == 3
puts "bar"
end
Executing this yields an error: [cc]5: syntax error, unexpected $end, expecting kEND[/cc]
At first I was a bit confused and tried to put an extra end keyword after the other one, just to see if it would work:
if 2 == 3
puts "foo"
else if 3 == 3
puts "bar"
end end
This "fixed" the problem. However this solution is not going to win any awards for elegance, so I dug around to see why the original code did not work. The reason is that I should have used the elsif keyword which is not equivalent of an if followed by an else clause.
if 2 == 3
puts "foo"
elsif 3 == 3
puts "bar"
end
The reason why my original implementation did not work, and why adding an extra end worked becomes much more obvious if we change the indentation of the original example:
if 2 == 3
puts "foo"
else
if 3 == 3
puts "bar"
# Missing end here!
end