Dex
Dex

Reputation: 12749

Ruby Regex: Math on Backreferences

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

Assume a raw file like this: 120m 90m

Should change to: 2h 1.5h

Upvotes: 2

Views: 401

Answers (2)

Shinya
Shinya

Reputation: 146

addition to sepp2k's answer.

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

Upvotes: 1

sepp2k
sepp2k

Reputation: 370162

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

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

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

Alternatively you could call to_s on the float and remove .0 if the string ends with ".0"

Upvotes: 6

Related Questions