现在我正在构建一个从电子表格导入数据的小应用程序,并且由于原始条目的性质,有一个字符串被读入,具有8½,2½等值.
我的目标是简单的功能就是将2½转换成float 2.5.
我试过了.to_f方法,但这让我感到奇怪的是2.02½的值.
这里的任何见解或建议将非常感谢!
解决方法
Unicode只支持一个
small number of vulgar fractions,所以一个简单的查找表会做的诀窍:
# You might want to double check this mapping vulgar_to_float = { "\u00BC" => 1.0 / 4.0,"\u00BD" => 1.0 / 2.0,"\u00BE" => 3.0 / 4.0,"\u2150" => 1.0 / 7.0,"\u2151" => 1.0 / 9.0,"\u2152" => 1.0 /10.0,"\u2153" => 1.0 / 3.0,"\u2154" => 2.0 / 3.0,"\u2155" => 1.0 / 5.0,"\u2156" => 2.0 / 5.0,"\u2157" => 3.0 / 5.0,"\u2158" => 4.0 / 5.0,"\u2159" => 1.0 / 6.0,"\u215A" => 5.0 / 6.0,"\u215B" => 1.0 / 8.0,"\u215C" => 3.0 / 8.0,"\u215D" => 5.0 / 8.0,"\u215E" => 7.0 / 8.0,"\u2189" => 0.0 / 3.0,}
然后,一点点正则表达式争吵把你的“数字”分开:
s = "2½" _,int_part,vulgar_part = *s.match(/(\d+)?(\D+)?/)
最后,把它们放在一起,正确地处理来自正则表达式的可能的nils:
float_version = int_part.to_i + vulgar_to_float[vulgar_part].to_f
记住nil.to_i是0,nil.to_f是0.0.