This:
class Loan
def initialize(amount, interest)
@amount = amount
@interest = interest
end
end
loan1 = Loan.new(100, 0.1)
Loan.each do |amount, interest|
debt = debt + amount + (amount*interest)
end
won't work because it's attempting to iterate over a class rather than an array or hash. Is there a away to iterate over all of the instances of a class?
Ruby doesn't automatically keep references to objects you create, it's your responsibility to write code that does. For example, when creating a new
Loan
instance you get an object. If you want aneach
method at the class level you'll need to track these by writing code that captures them:You must manually retain these because otherwise the garbage collector will pick up and destroy any un-referenced objects when they fall out of scope.
You can do something like this: Add a few accessors for
amount
andinterest
then use theObjectSpace
object along withinject
to sum up your debts.