我打了一個API,當沒有什麼返回時,它拋出一個「沒有方法nilClass
」錯誤。所以我添加了一堆if
/else
語句來處理這個問題。以下是我的代碼。語法錯誤,意外的關鍵字結束,期待')'結束
現在,我得到一個錯誤:
syntax error, unexpected keyword_end, expecting ')' end
因爲這是工作,我覺得我的路都很好。我在下面的視圖中標記了導致錯誤的行。當我刪除end
,它仍然拋出錯誤:
main_controller.rb
def money
@first = params[:first_name]
@last = params[:last_name]
@politician = JSON.load(open("http://..."))
if @politician.empty?
@politician = "Enter a politician's name."
else
@year = params[:year]
@pol_id = @politician[0]["id"]
@breakdown = JSON.load(open("http://..."))
if (@breakdown["Individuals"]).nil?
@individuals_money = 0
@individuals = 0
else
@individuals_money = (@breakdown["Individuals"][1]).to_f
@individuals = @breakdown["Individuals"][0]
end
if (@breakdown["PACs"]).nil?
@pacs_money = 0
@pacs = 0
else
@pacs_money = (@breakdown["PACs"][1]).to_f
@pacs = @breakdown["PACs"][0]
end
@total_money = @individuals_money + @pacs_money
@top_contributors = JSON.load(open("http://..."))
end
end
money.html.erb
<div class = "col-md-6">
<% if @politician == "Enter a politician's name." %>
<br />
<p><%= @politician %></p>
<% else %>
<h3><%= @politician[0]["name"] + " for " + @year %></h3>
<p><%= number_to_currency(@total_money) + " Total received"%></p>
<p><%= number_to_currency(@individuals_money) + " from " + number_with_delimiter(@individuals, :delimiter => ',') + " contributors" %></p>
<p><%= number_to_currency(@pacs_money + " from " + @pacs + " PACs" %></p>
<h4>Top Contributors</h4>
<% y = 0 %>
<% for y in 0..9 %>
<p><%= (y+1).to_s + ". " + @top_contributors[y]["name"].to_s + " " + number_to_currency(@top_contributors[y]["total_amount"].to_i) %></p>
<% end %>
<% end %> <<<<==== ***This is the line throwing the error***
</div>
這是因爲丟失了'如果else'在'money'方法 – usha
之類的東西'如果(@breakdown [ 「政治行動委員會」])爲零的''end'是壞的形式,它會導致你的'else'是雙重否定的(「If * that * is not not defined」)。它可以更好地表達爲「如果@ breakdown [」PACs「]'與條款顛倒過來。 – tadman
同樣值得注意的是,如果你的縮進被修正了,這個錯誤會更加明顯。你最終會習慣Ruby用'if'''end'對創建的模式。 – tadman