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

D20b852813b13faf3d603709ca822525?d=identicon&s=25 Emil Kampp (emilkampp)
on 2014-03-12 20:32
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!

Cheers,

Emil
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2014-03-12 22:00
Something like this should do it:
"1/50.0".gsub( /\d+\.?\d*/ ) { |num| num.to_f }
D20b852813b13faf3d603709ca822525?d=identicon&s=25 Emil Kampp (emilkampp)
on 2014-03-12 22:08
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) ?
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2014-03-12 22:52
Try it for yourself, the same code works:

"(1.0/50.0)*(Math.sqrt(5.0)*Math.sqrt(x+125.0)+25.0)"
D20b852813b13faf3d603709ca822525?d=identicon&s=25 Emil Kampp (emilkampp)
on 2014-03-13 06:30
Great. Thanks! :)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.