Aug*_*aas 12
发布第二个答案,作为慢性(我的原始答案建议)不会给你时间戳而是时间戳.
这是我的解析器.
class TimeParser
TOKENS = {
"m" => (60),
"h" => (60 * 60),
"d" => (60 * 60 * 24)
}
attr_reader :time
def initialize(input)
@input = input
@time = 0
parse
end
def parse
@input.scan(/(\d+)(\w)/).each do |amount, measure|
@time += amount.to_i * TOKENS[measure]
end
end
end
Run Code Online (Sandbox Code Playgroud)
战略相当简单.拆分"5h"成["5", "h"],确定有多少秒"h"表示(TOKENS),并且量增加@time.
TimeParser.new("1m").time
# => 60
TimeParser.new("1m wtf lol").time
# => 60
TimeParser.new("4h 30m").time
# => 16200
TimeParser.new("1d 4h").time
# => 100800
Run Code Online (Sandbox Code Playgroud)
它也不应该太难处理"1.5h",看到代码库就像它一样简单.