假设@houses 数组设置如下:
house1.price = 10
house2.price = 20
house3.price = 30
@houses << house1
@houses << house2
@houses << house3
这是我们计算的起点,我们想要找到房子的平均价格:
total = 0
average = 0
for h in @houses
total += h.price
end
average = total/@houses.size
这似乎是为了获得一个平均值而进行的大量输入。
有没有更好的办法?