如何遍历类的成员

这个:

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 

将无法工作,因为它试图迭代一个类而不是数组或散列。 是否需要迭代一个类的所有实例?

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 

您必须手动保留这些,否则垃圾收集器会在超出范围时拾取并销毁任何未引用的对象。

你可以这样做:为amountinterest添加一些访问器,然后使用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