此:
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
将无法工作,因为它试图迭代一个类而不是数组或散列。是否需要迭代所有类的实例?
答案 0 :(得分:5)
Ruby不会自动保留对您创建的对象的引用,您有责任编写具有此功能的代码。例如,在创建新的Loan
实例时,您将获得一个对象。如果您想在课程级别使用each
方法,则需要通过编写捕获它们的代码来跟踪这些方法:
class Loan
def self.all
# Lazy-initialize the collection to an empty array
@all ||= [ ]
end
def self.each(&proc)
@all.each(&proc)
end
def initialize(amount, interest)
@amount = amount
@interest = interest
# Force-add this loan to the collection
Loan.all << self
end
end
您必须手动保留这些,否则垃圾收集器会在超出范围时拾取并销毁任何未引用的对象。
答案 1 :(得分:1)
您可以执行以下操作:为amount
和interest
添加一些访问者,然后使用ObjectSpace
对象和inject
来累计您的债务。
class Loan
attr_accessor :amount, :interest
def initialize(amount, interest)
@amount = amount
@interest = interest
end
end
loan1 = Loan.new(100, 0.1)
loan2 = Loan.new(200, 0.1)
debt = ObjectSpace.each_object(Loan).inject(0) { |sum, obj|
sum + obj.amount + obj.amount * obj.interest
}
debt #=> 330.0