Skip to content

Instantly share code, notes, and snippets.

@tim-evans
Created February 19, 2016 19:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim-evans/d0ba1e8f05a55b76c49c to your computer and use it in GitHub Desktop.
Save tim-evans/d0ba1e8f05a55b76c49c to your computer and use it in GitHub Desktop.
Golang style duration parsing in Ruby
class Duration
def initialize(number_in_ms)
@value = number_in_ms
end
def self.parse(string)
value = string.scan(/([\d.-]+)(ms|s|m|h|d)/).reduce(0) do |total, parsed_duration|
number, unit = parsed_duration
total + case unit
when 'ms'
number.to_i
when 's'
number.to_i * 1_000
when 'm'
number.to_i * 60_000
when 'h'
number.to_i * 3_600_000
when 'd'
number.to_i * 86_400_000
end
end
self.new(value)
end
def milliseconds
@value
end
def seconds
@value / 1_000
end
def minutes
@value / 60_000
end
def hours
@value / 3_600_000
end
end
@ksin
Copy link

ksin commented Feb 22, 2016

Very Ruby. 👍

@KeithYJohnson
Copy link

coooool

@shyshy
Copy link

shyshy commented Feb 22, 2016

I'm thinking about making this into a factory. Gonna privatize the new method so people can't call it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment