如何遍历类的成员 [英] How to iterate through members of a class
问题描述
这:
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不会自动保留对象的引用创建,编写代码是你的责任。例如,在创建新的 Loan
实例时,您将获得一个对象。如果你想在类级别使用每个
方法,你需要通过编写捕获它们的代码来跟踪它们:
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 an each
method at the class level you'll need to track these by writing code that captures them:
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
您必须手动保留这些,否则垃圾收集器当它们超出范围时,它将拾取并销毁任何未引用的对象。
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.
这篇关于如何遍历类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!