这个:
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
Run Code Online (Sandbox Code Playgroud)
将无法工作,因为它试图迭代一个类而不是数组或散列.是否需要迭代一个类的所有实例?
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
Run Code Online (Sandbox Code Playgroud)
您必须手动保留这些,否则垃圾收集器会在超出范围时拾取并销毁任何未引用的对象.