如何解析ruby中的天/小时/分钟/秒? [英] How to parse days/hours/minutes/seconds in ruby?
本文介绍了如何解析ruby中的天/小时/分钟/秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有宝石或用于解析像4小时30分,1小时4小时等字符串的东西 - 有点像JIRA或任务计划人员的估计,也许是国际化?
class TimeParser
TOKENS = {
m=> > (60),
h=> (60 * 60),
d=> (60 * 60 * 24)
}
attr_reader:time
def初始化(输入)
@input =输入
@time = 0
parse
end
$ b $ def defrse
@ input.scan(/(\ d +)(\w)/)。each do | amount,测量|
@time + = amount.to_i * TOKENS [measure]
end
end
end
策略非常简单。将5h
分解为 [5,h]
,定义多少秒h
表示( TOKENS
),并将该金额添加到 @time
中。
TimeParser.new(1m)。time
#=> 60
TimeParser.new(1m wtf lol)。time
#=> 60
TimeParser.new(4小时30分钟)。时间
#=> 16200
TimeParser.new(1d 4h)。time
#=> 100800
它不应该太难处理1.5h
要么看到代码库是如此简单。
Is there a gem or something to parse strings like "4h 30m" "1d 4h" -- sort of like the estimates in JIRA or task planners, maybe, with internationalization?
解决方案
Posting a 2nd answer, as chronic (which my original answer suggested) doesn't give you timespans but timestamps.
Here's my go on a parser.
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
The strategy is fairly simple. Split "5h"
into ["5", "h"]
, define how many seconds "h"
represents (TOKENS
), and add that amount to @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
It shouldn't be too hard making it handle "1.5h"
either, seeing the codebase is as simple as it is.
这篇关于如何解析ruby中的天/小时/分钟/秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文