Jes Jes - 1 year ago 56
Ruby Question

Ruby - how to add phonecall's length? CSV file

I have class

- it represents single phonecall with certain number of minutes/seconds, date of the call etc. I want to sum length of calls for given day.
Problem is my data is in string format, I'm formatting it with various
options and many different things.
But my main problem is, how to sum them? I need something like Ruby's
but smart enough to know 60 seconds is one minute.
One additional problem is I'm reading from .CSV file, turning every row into Hash, and making Call objects out of it.
Any hints? :)

Answer Source

I suggest to store the duration of a call as a number of second in an integer. Because that would allow you to easily run calculation in the database.

But if you prefer to keep the string representation you might want to use something like this:

# assuming `calls` is an array of call instances and the 
# duration of the call is stores an attribute `duration`
total = calls.sum do |call|
  minutes, seconds = call.duration.split(':')
  minutes * 60 + seconds

# format output
"#{total / 60}:#{total % 60}"

Please note that the sum method is part of ActiveSupport. When you are using pure Ruby without Rails you need to use this instead:

total = calls.inject(0) do |sum, call|
  minutes, seconds = call.duration.split(':')
  sum + minutes * 60 + seconds
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download