开发者社区> 问答> 正文

无法对浮点迭代求和

ruby -v 2.3.7 (sqlite3与较新的ruby -v存在兼容性问题) sqlite3 -v 3.22 sqlite -v 2.8 lsb_release -a 18.04

我尽可能地浓缩了代码。

def some_method(info_hash)

...
db.results_as_hash = true
sum = 0
db.transaction
db.execute2 "CREATE table if not exists a_table(Id INT PRIMARY KEY, Type TEXT, Month TEXT, Amount FLOAT, TOTAL FLOAT)"
db.execute2 "INSERT into a_table(Type, Month, Amount) values(:Type , :Month , :Amount)", info_hash[:category], info_hash[:month], info_hash[:amount]
get_amt =  db.prepare "SELECT Amount from a_table WHERE Type = :Type" 
get_amt.execute info_hash[:category]
get_amt.each do |g| 
    sum += g #here I get a NoMethodError for Nil:NilClass
end
db.execute2 "INSERT into bills(Total) values(:sum)", sum
db.commit
...

end
我主要使用这种execute2方法。我依赖于execute我需要忽略标题的方法,例如在我的get_amt.each块中。

我想sum在Amount列Type。但是NoMethodError当我跑我的时候,我遇到了block。

完整的错误是: undefined method '+' for nil:NilClass (NoMethodError)

请告知我哪里出错了。

编辑: 我重写了代码以反映@Shawn的建议:

def some_method(info_hash)

    ...
    db.transaction
    db.execute2 "CREATE table if not exists a_table(Id INTEGER PRIMARY KEY, Type TEXT, Month TEXT, Amount FLOAT, Total FLOAT)"
    db.execute2 "INSERT into a_table(Type, Month, Amount) values(:Type , :Month , :Amount)", info_hash[:category], info_hash[:month], info_hash[:amount]
    get_amt =  db.execute2 "SELECT sum(Amount) from a_table WHERE Type = :Type", info_hash[:category]
    db.execute2 "INSERT into a_table(Total) values(:get_amt)", get_amt
    db.commit
    ...

end
这产生了 sqlite3 Exception Index out of range

展开
收起
小六码奴 2019-04-10 13:36:21 1875 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
新量⼦⾰命与量⼦计算 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载