2014-07-16 82 views
0

我打了一個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> 
+0

這是因爲丟失了'如果else'在'money'方法 – usha

+2

之類的東西'如果(@breakdown [ 「政治行動委員會」])爲零的''end'是壞的形式,它會導致你的'else'是雙重否定的(「If * that * is not not defined」)。它可以更好地表達爲「如果@ breakdown [」PACs「]'與條款顛倒過來。 – tadman

+2

同樣值得注意的是,如果你的縮進被修正了,這個錯誤會更加明顯。你最終會習慣Ruby用'if'''end'對創建的模式。 – tadman

回答

1

我想我看到您對此的語法錯誤line: <p><%= number_to_currency(@pacs_money + " from " + @pacs + " PACs" %></p>

number_to_currency沒有右括號。它應該是:?

<p><%= number_to_currency(@pacs_money) + " from " + @pacs + " PACs" %></p>

+0

聖潔的廢話,就是這樣!非常感謝。我今天花了幾個小時盯着這段代碼,並不明白爲什麼我得到這個'結束'錯誤。現在我知道它可以是任何東西。感謝幫助新手。 :) – David

+1

在那裏我自己,朋友。錯誤消息中的「期待」)部分是你最大的線索:尋找一個'('沒有')',你已經發現錯誤 - 至少這是我對這些語法錯誤的經驗。它通常與發現錯誤的行號無關。這就是'''缺少問題的代碼行。 – digijim

+0

哇,謝謝。我想我沒有意識到這一點。我一定會關注未來的人。再次感謝您花時間幫助我並提供解釋! – David

相關問題