gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
In Ruby language how to convert duration (given in seconds) to format "<min>:<sec>"
- User
In Ruby language how to convert duration (given in seconds) to format ":"
- Assistant
In Ruby, you can convert a duration given in seconds to a format like
<min>:<sec>using integer division and modulus to separate the minutes and seconds. Here's a simple way to achieve that:rubydef format_duration(seconds) minutes = seconds / 60 remaining_seconds = seconds % 60 formatted_duration = format("%d:%02d", minutes, remaining_seconds) formatted_duration end puts format_duration(123) # Output will be "2:03"In this code:
minutes = seconds / 60uses integer division to calculate the number of complete minutes.remaining_seconds = seconds % 60calculates the leftover seconds after accounting for the full minutes.format("%d:%02d", minutes, remaining_seconds)formats the string so that minutes are displayed as a decimal and seconds are zero-padded to two digits where necessary. This ensures that single-digit seconds are correctly formatted as:0x(e.g.,2:03).
The method thus converts a given numeric input of seconds into the desired format.