How would I xetract all numbers and floats from a string?

I have a user inputted string, which I would like to extract all numbers
and floats from. I then need to coerce those numbers (or floats) into
floats, and reinsert them into the string again.

I should be able to transform something like 1/50.0 to 1.0/50.0.

Thanks in advance!



Something like this should do it:
“1/50.0”.gsub( /\d+.?\d*/ ) { |num| num.to_f }

Joel, thanks for you’r input. What if the case is a bit more
complicated? Something like
(1/50.0)*(Math.sqrt(5)*Math.sqrt(x+125.0)+25) ?

Try it for yourself, the same code works:


Great. Thanks! :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs