2012-08-23 46 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

相关问题