如何通过类的成员进行迭代(How to iterate through members of a c

2019-10-29 08:01发布

这个:

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

因为它试图遍历一个类,而不是一个数组或哈希将无法正常工作。 是否有一个客场遍历所有类的实例?

Answer 1:

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

您必须手动保留这些,否则垃圾收集器会拾起并摧毁任何未引用的对象,当他们掉下来的范围。



Answer 2:

你可以这样做:添加了几个存取的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


文章来源: How to iterate through members of a class