Ruby时间值数组的平均值(fixnums)

时间:2011-10-18 21:45:19

标签: ruby-on-rails arrays time

希望获得平均持续时间,持续时间为1.day,3.months,2.weeks格式..

# provided array
a = [1.day, 3.days, 1.week, 4.days]

# desired output
a.average = "3 days"

我尝试过任何方式在几秒钟内输出结果......例如:

a.inject(:+) = "15 days"
a.inject(:+) / a.size = 324000

我看过Linguistics gem,但它只输出一个数字(三十二万四千)

2 个答案:

答案 0 :(得分:3)

def average_days(a)
  seconds = a.inject(:+) / a.size
  minutes = seconds / 60
  days    = (minutes / 1440).round
  "#{days} days"
end

答案 1 :(得分:1)

> a = [1.day, 3.days, 1.week, 4.days]
> (a.inject(0.0) {|sum, n| sum + n} / a.size) / (60 * 60 * 24)
 => 3.75 

如果你坚持。无论你想要圆形和/或截断。

((a.inject(0.0) {|sum, n| sum + n} / a.size) / (60 * 60 * 24)).days