【问题标题】:unable to sum a float iteration无法对浮点迭代求和
【发布时间】:2019-08-29 01:57:38
【问题描述】:

ruby -v 2.3.7(sqlite3 与较新的 ruby​​ -v 存在兼容性问题) sqlite3 -v 3.22sqlite -v 2.8lsb_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 AmountType。但是当我运行block 时遇到了NoMethodError

完整的错误是: 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

【问题讨论】:

  • @anothermh 很抱歉那个错字(肯定错过了十几次!!!)已更正
  • Sqlite 2.8? ... 为什么?那是从 2003 年开始的!
  • 为什么不SELECT sum(amount) FROM a_table WHERE ...
  • 哦!返回的行中的金额是否有空值?

标签: ruby sqlite each nomethoderror


【解决方案1】:
db.execute2 "INSERT into a_table(Total) values(:get_amt)", get_amt[1][0]

基本上语句get_amt = db.execute2 "SELECT sum(Amount) from a_table WHERE type = :type", hash_info[category] 将超过1 个值写入get_amt 变量。 必须为变量提供INSERT 使用的特定 值的rowcolumn。因此get_amt[1][0] 或第一行(标题行之后的下一行)和第一列。

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 2020-09-10
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多