2012-04-26 13 views
3

ルビーでエレガントな正規表現があり、文字列中のすべての°C〜°Fを置換すると同時にユニットを変換しますか?例:Ruby:文字列の温度単位を変換する方法は?

"今日は25℃と明日27℃です。" "今日は77°Fと明日81°Fである。"

のようなものになるはずです

+2

なぜ奇妙な測定単位が必要なのですか? – Joey

+1

私に尋ねないで、奇妙な人に尋ねなさい;-) – dokaspar

答えて

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. 
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を使用)が、うまくいけば、これは可能であるかもしれないものを見るのに十分なはずです。

関連する問題