gpt4 book ai didi

ruby-on-rails - 简单计算会导致Ruby中的语法错误

转载 作者:行者123 更新时间:2023-12-03 08:31:06 26 4
gpt4 key购买 nike

我在Ruby中有一个简单的财务应用程序,可以跟踪用户的支出并根据这些支出生成报告。

费用属于不同的类别,这会影响每种费用中的税金。

在生成费用报告的代码中,我有以下内容:

  tax_totals = [0] * 13
totals = [0] * 13
expenses.each do |expense|
tax_ratio = tax_rate/(1+tax_rate)
category = Category.find(expense.category_id).first
tax_ratio *= category.tax_rate.to_f / 100
if !expense.rate_id.nil?
subcategory = Rate.where("id = ?", expense.rate_id).first
tax_ratio *= subcategory.tax_rate.to_f
end
tax_totals[expense.transaction_date.to_date.month] +=
(expense.amount * tax_ratio)
totals[expense.transaction_date.to_date.month] += expense.amount
end

我在 tax_ratio = tax_rate/(1+tax_rate)上不断收到语法错误:
syntax error, unexpected '(', expecting keyword_end

如果删除该行,则错误将移至 tax_ratio *= category.tax_rate.to_f / 100行:
syntax error, unexpected tINTEGER, expecting keyword_end

我没有想法,这是从哪里来的。我完全看不出代码有什么问题。我在多个函数中有非常相似的代码,每个函数所做的计算略有不同。但是只有一个是一个问题。

也许是因为缺乏咖啡因。这段代码有什么问题吗?文件中是否可能有其他原因导致这种情况?如何进行调试?

干杯!

编辑:我想通了。 Ruby Noob错误。请参阅下面的答案。

最佳答案

如上所述,这是有效的Ruby。我能够将您的代码放入方法中并调用它。见下文:

require 'active_support/all'
require 'rspec'

class Category
def self.find(category_id)
[new]
end

def tax_rate
0.5
end
end

class Rate
def self.where(*args)
[new]
end

def tax_rate
0.5
end
end

def ratio(expenses, tax_rate)
tax_totals = [0] * 13
totals = [0] * 13
expenses.each do |expense|
tax_ratio = tax_rate/(1+tax_rate)
category = Category.find(expense.category_id).first
tax_ratio *= category.tax_rate.to_f / 100
if !expense.rate_id.nil?
subcategory = Rate.where("id = ?", expense.rate_id).first
tax_ratio *= subcategory.tax_rate.to_f
end
tax_totals[expense.transaction_date.to_date.month] +=
(expense.amount * tax_ratio)
totals[expense.transaction_date.to_date.month] += expense.amount
end
end


describe "#ratio" do

let(:expense) do
double("expense", category_id: 5, rate_id: 6, transaction_date: 5.days.ago, amount: 5)
end
let(:expenses) { [expense] }
let(:tax_rate) { 0.25 }

it "should run" do
ratio(expenses, tax_rate)
end
end

关于ruby-on-rails - 简单计算会导致Ruby中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14741131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com