2012-08-23 58 views
0

我從數據庫中檢索的浮點值,並試圖將其添加到浮點類型值,我得到一個錯誤:in '+': Array cant be coerced into Float (TypeError)結果 - 陣列不能強迫浮動(類型錯誤)

total = 0.0 
db = SQLite3::Database.open "Checkout.sqlite" 

for i in [email protected] 
    tempPrice = db.execute "SELECT price FROM Products WHERE product_code = ?", @items[i] 
    total = total + tempPrice 
end 

回答

0
total = 0.0 
db = SQLite3::Database.open "Checkout.sqlite" 

for i in [email protected] 
    db.execute("SELECT price FROM Products WHERE product_code = ?", @items[i]) do |row| 
     total = total + row[0] 
    end 
end 
+0

謝謝你的工作。 – Neeta

1

tempPrice是數組,如果結果可以有多個值,則應該使用tempPrice[0],如果您確定它只有1個值,或者可以使用tempPrice.sum

UPD: 嘗試

total = 0.0 
db = SQLite3::Database.open "Checkout.sqlite" 

@items.each do |item| 
    db.execute("SELECT price FROM Products WHERE product_code = ?", item) do |row| 
     total = total + row[0] 
    end 
end 
+0

我試圖tempPrice [0]前一段時間,並得到了同樣的錯誤,我試圖tempPrice.sum並獲得:未定義的方法 '和' 對[[45.00] ]:Array(NoMethodError) – Neeta

+0

嘗試調試,將'p tempPrice'放在'total = total + tempPrice'之前 –

+0

除了之前所說的內容之外,它不會說其他任何內容:在'total'中的'block in total'中' – Neeta

相關問題