How to iterate through members of a class

2019-09-15 05:59发布

问题:

This:

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?

回答1:

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.



回答2:

You can do something like this: Add a few accessors for amount and interest then use the ObjectSpace object along with inject to sum up your debts.

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