0

我有一个简单的 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

我不知道这是从哪里来的。我根本看不出代码有什么问题。我在多个函数中有非常相似的代码,每个函数的计算略有不同。但只有这一个是一个问题。

也许是缺乏咖啡因。这段代码有问题吗?文件中是否还有其他原因导致此问题?如何继续调试?

干杯!

编辑:我想通了。红宝石菜鸟错误。请参阅下面的答案。

4

2 回答 2

1

如上所述,这是有效的 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
于 2013-02-07T00:01:03.107 回答
0

我是 Ruby 和 Rails 的新手,对我来说这是最奇怪的事情。

错误来自如此无辜的线路,我什至没有费心将它包含在我原来的问题中。

tax_rate是一个被传递给方法的变量。它以整数形式存储在数据库中,因此我需要将其转换为小数点。这是更完整的代码:

  tax_rate = tax_rate.to_f /100
  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

第一行是 Ruby 不喜欢的,我仍然不知道为什么。但是你不能myVar /100说它必须是myVar / 100,甚至是数字和数字myVar/ 100之间绝对需要有一个空格/

于 2013-02-07T19:29:05.453 回答