# Convert speed to pace programmatically using Ruby

I came across a problem while working on my little side project Strafforts (A Visualizer for Strava Estimated Best Efforts and Races), that how to convert speed (`m/s` in this case) to pace (`min/km` or `min/mile`) programmatically using Ruby.

## Calculate time spend per distance (kilometre/mile)

Strava Activity API provides a field for athlete's average speed during this activity. It is a float number for meters per seconds (i.e. the unit of the speed is `m/s`).

For example, if the speed is 4 meters per seconds and the target pace unit is `min/km`. Then the first step is to find out how long does it take reach the target distance (one kilometre) with this speed.

This is simple math: `1000 / 4 = 250 (seconds)`.

If the target pace unit is `min/mile` (minutes per mile), then it's `1609.344 / 4 = 402.336 (seconds)` for one mile.

## Convert seconds to pace

The second step is to convert the total seconds used per distance into pace. Note that time is base 60, while meter is base 10.

## What about speed unit is mph or km/h?

The concept will be exactly the same:

1. Figure out the time per distance.
2. Convert time to pace.

For example, to convert 12 km/h to pace:

12 km/h is 12 kilometres (7.45645 miles) per 3600 seconds.
So it's 3600 / 12 = 300 (seconds per km), 3600 / 7.45645 = 482.803 (seconds per mile).
Then use the modulo logic above to convert seconds into pace, which is 5:00 min/km or 8:03 min/mile.