Ruby Regex: Math on Backreferences

I need to replace all minutes with hours in a file.

Suppose such a raw file: 120m 90m

Should change to: 2h 1,5N

+2
source share
2 answers

If you can live with it printing "2.0" instead of "2", you can simply do:

"120m 90m".gsub(/(\d+)m/) { "#{$1.to_f / 60.0}h"}
#=> "2.0h 1.5h"

If you need to print it without ".0", you need to check if the number is equally divisible by 60, and if so return $1.to_i / 60instead $1.to_f / 60.0.

Alternatively, you can call to_sin the float and delete .0if the line ends with ".0"

+6
source

addition to sepp2k answer.

"120m 90m".gsub(/(\d+)m/) { "#{($1.to_f / 60.0).to_s.gsub(/\.0$/, '')}h"}
#=> "2h 1.5h"
+1
source

All Articles