How to iterate through members of a class

跟風遠走 提交于 2020-01-07 04:38:24

问题


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


来源:https://stackoverflow.com/questions/44961987/how-to-iterate-through-members-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!