Human readable duration format

題目:

Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.

The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.

It is much easier to understand with an example:

  format_duration(62)    # returns "1 minute and 2 seconds"
  format_duration(3662)  # returns "1 hour, 1 minute and 2 seconds"

Note that spaces are important.

Detailed rules

The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.

Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.

A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.

A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.

For the purpose of this Kata, a year is 365 days and a day is 24 hours.

思路:

只是單純把數字轉成字串,但是要處理每一個字中間的", "和最後的" and " 還有複數需要把字串最後加上s,所以另外弄一個method來處理這塊

使用到的語法:

hash的使用 array.pop

程式碼:

def format_duration(seconds)
  seconds == 0 ? (return "now") : false
  tmp = last = []
  str = {}
  yr = seconds / (365*24*60*60)
  day = (seconds % (365*24*60*60)) / (24*60*60)
  hour = ((seconds % (365*24*60*60)) % (24*60*60)) / 3600
  min = (((seconds % (365*24*60*60)) % (24*60*60)) % 3600) / 60
  sec = (((seconds % (365*24*60*60)) % (24*60*60)) % 3600) % 60
  str["year"] = yr
  str["day"] = day
  str["hour"] = hour
  str["minute"] = min
  str["second"] = sec
  str.delete_if {|k,v| v == 0}
  str.each do |k,v|
    tmp << pluralize(v,k)
  end
  tmp.size == 1 ? (return tmp[0]) : (last = tmp.pop)
  return tmp.flatten.join(", ") + " and " + last
end

def pluralize(num,string) 
  if num == 0
    return ""
  elsif num == 1
    return "#{num} #{string}"
  else
    return "#{num} #{string}s"
  end
end

results matching ""

    No results matching ""