0

我从数据库中检索了一个 Float 值并尝试将其添加到 Float 类型值中,但出现错误:in '+': Array cant be coerced into Float (TypeError)

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

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

2 回答 2

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
于 2012-08-23T10:37:54.407 回答
0
total = 0.0
db = SQLite3::Database.open "Checkout.sqlite"

for i in 0..@items.length
    db.execute("SELECT price FROM Products WHERE product_code = ?", @items[i]) do |row|
        total = total + row[0]
    end
end
于 2012-08-23T10:52:38.553 回答