Ruby 每次调用方法时都要更新/重新加载其自身?红宝石

Ruby 每次调用方法时都要更新/重新加载其自身?红宝石,ruby,math,Ruby,Math,我的长期目标是在ruby程序中复制,然后复制到rails应用程序中 目前,我正试图确定这两个债务中哪一个利息最高,然后从该债务中减去最低金额以及该人愿意支付的任何额外金额,并从其他债务中减去最低价值 例如: card = balance: $10,000, Minimum: $200, i% = 20% loan = balance: $40,000, Minimum: $400, i% = 5% payments made per month = $1000 在这种情况下,该计划将首先每月从

我的长期目标是在ruby程序中复制,然后复制到rails应用程序中

目前,我正试图确定这两个债务中哪一个利息最高,然后从该债务中减去最低金额以及该人愿意支付的任何额外金额,并从其他债务中减去最低价值

例如:

card = balance: $10,000, Minimum: $200, i% = 20%
loan = balance: $40,000, Minimum: $400, i% = 5%
payments made per month = $1000
在这种情况下,该计划将首先每月从卡中取出600美元(1000-($200+$400)+$200),直到余额为0,然后取出1000美元(1000-$400+$400),直到贷款还清,并返回所需的月数

目前,考虑到债务余额,我正试图获得每月要减去的金额,并在调用该方法时进行此更新-然而,这似乎不起作用,两种债务的金额都将保持在400美元(snowball_金额方法)编辑:修复了缺少方法的问题。需要将attr_reader更改为attr_accessor。另外,由于某种原因,当我将一个债务对象传递给最高利息时,我得到一个未定义的方法“balance=”错误。我将非常感谢您的帮助

创建一个债务类别

class Debt
  def initialize(balance: b, monthly_payment: m, annual_interest_rate: a)
    @balance = balance
    @monthly_min = monthly_payment
    @int_rate = annual_interest_rate
  end
  attr_reader :monthly_min, :balance, :int_rate
end
创建两个债务对象

@debt1 = Debt.new(balance: 14000.0, monthly_payment: 200.0, annual_interest_rate: 0.06)
@debt2 = Debt.new(balance: 40000.0, monthly_payment: 400.0, annual_interest_rate: 0.08)
把它们排成一排

@debts_array = [@debt1, @debt2]
设定员工每月愿意支付的金额

@payment = 1000.0
确定支付的额外金额,即每月至少支付一笔债务,前提是该债务的余额超过0

def snowball_amount
  @payments_less_mins = @payment
  @debts_array.each do |debt|
    if debt.balance <= 0
      @payments_less_mins
    elsif debt.balance > 0
      @payments_less_mins = @payments_less_mins - debt.monthly_min
    end
  end
  puts @payments_less_mins
  return @payments_less_mins
end
确定还清债务需要多长时间。当债务余额大于0时,首先根据增加的利息更新余额,然后从债务余额中减去每月最低付款额和余额中的雪球(额外金额)。然后将债务余额设置为0

def highest_interest(debt, snowball)
  months_to_pay = 0
  while debt.balance > 0
    debt.balance = compounding_interest(debt.balance, debt.int_rate)
    debt.balance = debt.balance - (debt.monthly_min + snowball)
    months_to_pay += 1
  end
  debt.balance = 0
  snowball_amount
  puts months_to_pay
end
确定哪些债务余额最高,然后对该债务采用最高利息法

def which_has_higher_interest
  debts_array = @debts_array.sort{|i| i.int_rate}.reverse!
  puts debts_array[0].balance
  debts_array.each do |debt|
    highest_interest(debt, snowball_amount)
  end
end
调用which_has_higher_interest方法

puts which_has_higher_interest

最高利息
方法的第3行、第4行和第7行中,您正在对
债务
对象调用名为
余额=
的方法,但您的
债务
对象没有这样的方法。您需要以某种方式定义它,可能是通过更改行

attr_reader :monthly_min, :balance, :int_rate


问题太长了。大多数人都不想读它。请说得更简洁些。
attr_reader :monthly_min, :balance, :int_rate
attr_reader :monthly_min, :int_rate
attr_accessor :balance