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.

1
  • 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. Commented Feb 6, 2017 at 15:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.