Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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]
Add a comment
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.
Float
String.to_f
You have 3 numbers there. Split them up, and simply call #to_f (meaning "to float") on each string.
#to_f
string = "00:00:30.04," strings = string.split ":" numbers = strings.map { |s| s.to_f } numbers # => [0.0, 0.0, 30.04]
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]
Required, but never shown
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.
Explore related questions
See similar questions with these tags.