Rabbott
Rabbott

Reputation: 4332

Ruby average value of array of time values (fixnums)

Looking to get the average duration, where duration is in the form of 1.day, 3.months, 2.weeks format..

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

# desired output
a.average = "3 days"

Any way I have tried results in a number of seconds being the output.. for instance:

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

I've looked at the Linguistics gem, but it only outputs the value as a number (three hundred and twenty four thousand)

Upvotes: 0

Views: 1536

Answers (2)

Unixmonkey
Unixmonkey

Reputation: 18784

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

Upvotes: 3

jdl
jdl

Reputation: 17790

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

If you insist. Round and/or truncate however you want.

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

Upvotes: 1

Related Questions