1

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

4

4 回答 4

2
s = "00:00:30.04,"
s.split(/[^\deE\.+-]/).map(&:to_f) # => [0.0, 0.0, 30.04] 
于 2013-02-04T21:23:24.097 回答
2
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

于 2013-02-04T21:30:19.970 回答
1

你那里有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]
于 2013-02-04T21:23:06.877 回答
1

如果分隔符始终是冒号或逗号,则可以使用以下内容:

"00:00:30.04,".split(/:|,/).map(&:to_f) #=> [0.0, 0.0, 30.04]
于 2013-02-04T21:53:32.173 回答