codeinspired codeinspired - 4 years ago 110
Ruby Question

Ruby: How to sum array of Time objects?

I have a CardioExercise model with a duration attribute (Ruby 2.2.4 Time datatype). I need to write a method to calculate the total duration of aerobic activity by a member during the past week.

Here's what I've got so far:

def minutes_cardio_exercise_last_week
array = @user.member.cardio_exercises.between_times(1.week.ago.beginning_of_week, 1.week.ago.end_of_week).map { |d| d[:duration] }
hour, min, sec = ??
(hour * 60 + min + sec / 60).round
end


In the Rails console, the array contains:

=> [2000-01-01 00:25:00 UTC, 2000-01-01 00:30:00 UTC, 2000-01-01 00:53:20 UTC]


Those are the time objects I'm expecting, but I can't figure out how to sum the values to get something like 108 minutes of aerobic activity last week?

During my research, I found two posts that address the issue using PHP. A third post is Ruby, but I can't figure out how to adapt the solution for my purpose.

How to Sum Time Value in Array |
How to sum time in array? |
Ruby: Average array of times

I appreciate any help and insight.

Answer Source
array.inject(0) { |sum, t| sum + ((t.hour * 60 + t.min + t.sec / 60).round) }

or even better if you have function to get minutes.

def minutes(t)
     (t.hour * 60 + t.min + t.sec / 60).round
end

def minutes_cardio_exercise_last_week
   array = @user.member.cardio_exercises.between_times(1.week.ago.beginning_of_week,            1.week.ago.end_of_week).map { |d| d[:duration] }
   array.inject(0) { |sum, t| sum + minutes(t) } 
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download