Ruby: how to convert temperature units to string?

Is there an elegant Ruby path with Ruby to replace all occurrences of ° C in ° F in a string (and at the same time convert units)? For instance:

"Today it is 25 ° C and tomorrow 27 ° C.

something like:

"Today it is 77 ° F and tomorrow 81 ° F."

+3
source share
2 answers
# -*- encoding : utf-8 -*-
def c2f(c)
  c*9.0/5+32
end

def convert(string)
  string.gsub(/\d+\s?°C/){|s| "#{c2f(s[/\d+/].to_i)}°F"}
end

puts convert("Today it is 25°C and tomorrow 27 °C.")
# result is => Today it is 77.0°F and tomorrow 80.6°F.
+3
source

The shape of the block String#gsublooks like you need:

s = "Today it is 25C and tomorrow 27 C." # 
re = /(\d+\s?C)/ # allow a single space to be present, need to include the degree character
s.gsub(re) {|c| "%dF" % (c.to_f * 9.0 / 5.0 + 32.0).round } #=> "Today it is 77F and tomorrow 81F."

I lost the degree symbol (I used Ruby 1.8.7, which is not very suitable for Unicode), but hopefully this should be enough to see what might be possible.

+1
source