你如何简明得到房子的数组的平均房价? [英] How do you concisely get the average house price from an array of houses?

查看:167
本文介绍了你如何简明得到房子的数组的平均房价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设@houses阵列设置如下:

  house1.price = 10
house2.price = 20
house3.price = 30
@houses<< house1
@houses<< house2
@houses<< house3

这是我们计算的起点,我们希望找到一个房子的平均价格:

 总= 0
平均= 0
在@houses ^ h
 总+ = h.price
结束
平均= total/@houses.size

这似乎是相当多的打字只是为了得到平均的。

有没有更好的办法?


解决方案

使用的 方法上可枚举集合。喷出让你在初始值传递给一个累加器'(0在此情况下),则适用于一些操作列表中的每个元素,并返回累加器要传递到下一次迭代的新值。

累加器。然后,从返回的最终值电话。

因此​​,在这种情况下,我们只是添加了所有的房价到累加器,那么最后由总数量除以。

您可以得到funkier大概COM preSS下来多用一些红宝石的skillz,但是这是可以理解的合理,并通过列表只迭代一次,加起来的值。

  @ houses.inject(0){|总,房子|总+ house.price} / @ houses.size

Assuming the @houses array is set up as follows:

house1.price = 10
house2.price = 20
house3.price = 30
@houses << house1
@houses << house2
@houses << house3

This is the starting point of our calculation and we want to find the average price of a house:

total = 0
average = 0
for h in @houses
 total += h.price
end
average = total/@houses.size

This seems like quite a lot of typing just to get an average.

Is there a better way?

解决方案

Use the inject method on an enumerable collection. Inject lets you pass in an initial value for an 'accumulator' (0 in this case), then apply some operation to each element in the list, and return a new value for the accumulator to be passed into the next iteration.

The final value of the accumulator is then returned from the inject call.

So in this case, we just add up all the house prices into the accumulator, then finally divide by the total number.

You can get funkier and probably compress it down more with some Ruby skillz, but this is reasonably understandable, and only iterates through the list once to add up the values.

@houses.inject(0){|total, house| total + house.price} / @houses.size

这篇关于你如何简明得到房子的数组的平均房价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆