sagarpandya82 sagarpandya82 - 4 months ago 8
Ruby Question

Is there an easy way to convert numbers to floats within a string?

I have a string

input = "2 + 3"
which I would like to convert to
"2.0 + 3.0"
. I have achieved this with the following two convoluted methods:

floats = input.scan(/\d+/).map(&:to_f)
operator = input.scan(/[+,\-,*,\/]/)
operator.unshift(floats.first.to_s)
.push(floats.last.to_s).join(' ')
#=> "2.0 + 3.0"


or:

input.split(/\s+/)
.map{|i| ['+','-','*','/'].include?(i) ? i : i.to_f }
.join(' ')
#=> "2.0 + 3.0"


Is there an easier or better way to do this?

Answer

You can try this also

> "2 + 3".scan(/\d+/).map(&:to_f).join(" + ")
=> "2.0 + 3.0"

After a advice from @sergio I try to do it as a gsub also inspire the above @mudasobwa answer..

> "2 + 3/4.5".gsub(/(?<!\.)\b[0-9]+\b(?!\.)/) {|i| i.to_f}
=> "2.0 + 3.0/4.5"

also test

> "25 + 13/4.5".gsub(/(?<!\.)\b[0-9]+\b(?!\.)/) {|i| i.to_f}
=> "25.0 + 13.0/4.5"