我认为这可能是您的累加器范围的问题,请考虑这个示例。
# example Organism class
class Organisim
attr_accessor :predict, :resources, :prediction
def initialize
@resources = 0
end
def predict
@prediction = rand(10)
@prediction
end
end
# initialize @organisims
@organisims = []
100.times do
@organisims << Organisim.new
end
puts "!!!! Starting Organisim Specific Run"
# iterate over array tracking organisim's resource
@organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
(p == r) ? org.resources += 1 : org.resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: n/a"
end
puts "!!!! Cumulative Resource Run"
# resources scoped outside the iteration loop as accumulator
overall_resources = 0
# re-initialize @organisims
@organisims = []
100.times do
@organisims << Organisim.new
end
@organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
#track class level resource
(p == r) ? org.resources += 1 : org.resources -= 1
#iterate accumulator
(p == r) ? overall_resources += 1 : overall_resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: #{overall_resources}"
end
第一个迭代循环就像(我认为)您在问题中遇到的那个,但是您正在更改organisim 对象实例中的资源。
您的累加器的第二次迭代超出了迭代的范围,因此它会随着对象的操作而增长和缩小。:-)