3

Ruby 是否有一种优雅的正则表达式来替换字符串中所有出现的°C 到°F(同时转换单位)?例如:

“今天是 25°C,明天是 27°C。”

应该导致类似:

“今天是 77°F,明天是 81°F。”

4

2 回答 2

3
# -*- 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.
于 2012-04-26T08:39:56.423 回答
1

看起来的块形式String#gsub是你需要的:

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."

我丢失了学位字符(我使用了 Ruby 1.8.7,它对 Unicode 不太友好),但希望这足以让我们了解可能发生的事情。

于 2012-04-26T08:33:33.983 回答