I am having a string with the following patter
"00:00:30.04,"
Which would be the smartest way to parse this string into a float?
best, phil
s = "00:00:30.04,"
s.split(/[^\deE\.+-]/).map(&:to_f) # => [0.0, 0.0, 30.04]
p "00:00:30.04,"[6,5].to_f # 30.04
p Float("00:00:30.04,"[6,5]) # 30.04
p "abcdefg"[6,5].to_f # 0.0
p Float("abcdefg"[6,5]) #ArgumentError
本质上:从位置 6 开始,长度为 5 的子字符串,并基于它返回一个浮点数。Float
然后更严格String.to_f
。
你那里有3个数字。将它们拆分,然后#to_f
在每个字符串上简单地调用(意思是“浮动”)。
string = "00:00:30.04,"
strings = string.split ":"
numbers = strings.map { |s| s.to_f }
numbers # => [0.0, 0.0, 30.04]
如果分隔符始终是冒号或逗号,则可以使用以下内容:
"00:00:30.04,".split(/:|,/).map(&:to_f) #=> [0.0, 0.0, 30.04]