2013-03-25 137 views
0

嘗試使用新的LearnStreet在線教程來學習Ruby。停滯在LearnStreet Ruby培訓。簡單的Ruby代碼第5課

你現在可以寫一個方法add_interest!在賬戶對象上,它取一個參數百分比並將該百分比的餘額添加到賬戶中?

提示2 調用具有參數的方法10

提示1個 百分比計算 - (@balance *百分比)/ 100

我嘗試:

def account.add_interest!(percentage) 
    (@balance * percentage)/100 
end 

account.add_interest!(10) 

我在想什麼?

回答

0

看來你需要設置@balance。您的方法add_interest!僅返回值,但不會將@balance實例變量設置爲新值。

def add_interest!(percentage) 
    interest = (@balance * percentage)/100 
    @balance = @balance + interest 
end 

可能會更好地工作。

在方法的末尾添加爆炸!是與其他Ruby開發人員溝通的常用方法,該方法會執行令人驚訝的操作,如永久變更對象。

+1

不,這不是什麼爆炸方法。爆炸法意味着該方法與非爆炸方法做同樣的事情,但以更令人驚訝的方式。如果還有相應的非爆炸方法,那麼應該只有一種爆炸方法,爆炸方法與突變無關。 – 2013-03-26 01:07:56

+0

將@balance設置爲(@balance * percentage)/ 100在這裏並沒有真正實現。這就像是說餘額等於餘額的百分比。 – DnfD 2013-03-27 15:45:25

+0

啊,大衛。我更關注於設置實例變量,並使用OP的原始代碼。感謝您指出。 – tbeseda 2013-03-28 16:00:00

0

我對Ruby非常陌生,但只是想打個招呼。讓我知道你是否有任何問題。我95%確定這可以重構。在learnstreet

class Account 
    def self.add_interest_to_current_balance(balance, percentage) 
    percentage_amount_in_dollars = (percentage * balance)/(100) 
    percentage_amount_in_dollars + balance 
    end 
end 

puts Account.add_interest_to_current_balance(500, 10) #should return 550 
+0

我相信LearnStreet應用程序查看實例變量以允許用戶完成練習,所以方法應該設置'@ balance'。 – tbeseda 2013-03-28 16:03:38

+0

哦好吧,我明白了,我從來沒有學過LearnStreet,所以idk。如果OP會發布他的包含@balance的方法,這將會有所幫助,那麼這將更容易理解。 – DnfD 2013-03-29 16:07:11

0

100%的工作

def account.add_interest!(percentage) 
    @balance = @balance + (@balance * percentage)/100 
end 

account.add_interest!(10) 

我被困在太,前:d

0

這對我的回答工作,不妨一試:

def add_interest!(percentage) 

    interest = (@balance * percentage)/100 

    @balance = @balance + interest 

end 

account.add_interest!(10)