2015-02-09 28 views
-1

我的長期目標是在紅寶石程序中複製this spreadsheet,然後複製到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_amount方法)。 編輯:修復了缺少方法問題。需要將attr_reader更改爲attr_accessor 也出於某種原因,當我將一個債務對象傳遞給highest_interest時,我得到一個未定義的方法'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 

確定被多少額外的祈禱,即@payment - 每債務每月最低,只有當債務的餘額超過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 

用於計算債務餘額當月

方法
def compounding_interest(balance, apr) 
    return balance * (1 + apr/12)**1 
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 
+0

問題太長。大多數人不會喜歡閱讀它。請使它更簡潔。 – sawa 2015-02-09 16:14:33

回答

1

在線路3,4,和你highest_interest方法7,要調用一個Debt對象上調用balance=方法,但你的Debt對象沒有這樣的方法。你需要以某種方式定義它,可能改變這一行

attr_reader :monthly_min, :balance, :int_rate 

attr_reader :monthly_min, :int_rate 
attr_accessor :balance 
+0

ahhh好吧給我一個去吧謝謝! – HarryLucas 2015-02-09 13:19:56

+0

謝謝你解決了這個問題! – HarryLucas 2015-02-09 13:28:20