I’m getting an error from one of my controller classes and I can’t figure out why. The error is:
SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end
Here is terms_controller.rb:
class TermsController < ApplicationController
def show
@term = Term.find(params[:id])
if @term.id == 1
@title = "Fall"
else if @term.id == 2
@title = "Winter"
else if @term.id == 3
@title = "Spring"
else if @term.id == 4
@title = "Summer"
end
end
end
My show page currently just consists of:
<h1> <%= @title %> </h1>
It’s probably something small that I’m just missing – thanks for your help!
The issue that there are not enough
endkeywords and it found$end(the token representing the end of the file) before it could find what it was looking for — anotherend. (The parser token for theendkeyword is either “keyword_end” or “Kend”, depending upon ruby version.)Each
ifexpression requires a matchingendkeyword.To get around this, use
elsifinstead ofelse if. It is part of the sameifconstruct and does not require a matchingend(only theifrequires the matchingend).Another option is
casewhich works well if all branches check the same conditional operand (xin this case):If you do want to use
else if(remember, eachifstarts a newifconditional construct) then make sure close each block that aifopens. I have indented the code to show this point better.Happy coding.
For the pedantic: there is also another form of
if, which isexpr if cond, which doesn’t have a matchingendas part of the syntax and the rules talked about above do not apply to it.In addition,
ifandcaseare just expressions in Ruby, so it might be more idiomatically written like thisThe
if/elsif/endsyntax can be used in the same way, but usingcaseavoids the repeated mentioning of@term.id. Another option is to use a Hash to perform this sort of simple mapping — or the mapping can be encapsulated in a separate method — but that is covered elsewhere 😉