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 Answers 4

2
s = "00:00:30.04,"
s.split(/[^\deE\.+-]/).map(&:to_f) # => [0.0, 0.0, 30.04] 
Sign up to request clarification or add additional context in comments.

Comments

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

Essentially: take a substring starting at position 6 with a length of 5 and return a float based on that. Float is stricter then String.to_f.

Comments

1

You have 3 numbers there. Split them up, and simply call #to_f (meaning "to float") on each string.

string = "00:00:30.04,"
strings = string.split ":"
numbers = strings.map { |s| s.to_f }
numbers # => [0.0, 0.0, 30.04]

Comments

1

if seperator is always colon or coma, you can use following:

"00:00:30.04,".split(/:|,/).map(&:to_f) #=> [0.0, 0.0, 30.04]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.