1

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.

Community
  • 1
  • 1
codeinspired
  • 366
  • 4
  • 16
  • Time is very much not the right class to use to represent durations. You will save yourself a lot of trouble (as you've already discovered) by just using an integer number of minutes. – Jordan Running Feb 06 '17 at 15:51

1 Answers1

2
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
Manikandan
  • 3,025
  • 2
  • 19
  • 28
  • Thanks @Manikandan. That did the trick! I had researched the inject method, but hadn't figured out how to use it. I'll read the docs on that method to get a better understanding. – codeinspired Feb 06 '17 at 15:26