From: "Michael W. Ryder" <_mwryder@...> Date: 2008-05-20T08:45:03+09:00 Subject: Re: Why doesn't Float() work the same as Integer()? Rimantas Liubertas wrote: >> If I use Float("17") it returns 17.0 and Float(0x11) returns 17.0, both as >> expected. > > Yes, because Kernel.Float knows how to convert string "17" to float > and number 17 > written as 0x11 to float. > >> Why doesn't Float("0x11") work? > > You answer that yourself. Unlike Kernel.Integer, Kernel.Float does not honor > radix indicators (0, 0b, 0x), thus string '0x11' is invalid for that method. > While '0x11'.to_f also does not know how to deal with this, it > silently returns 0.0. > Kernel.Float is different in that way, that it rises an exception when > given string is invalid. > >> As Ruby doesn't appear to handle >> Floats of bases other than 10 (or at least I haven't figured out how to yet) >> I can see it choking on Float("0x11.34") but it shouldn't choke on >> Float("0x11"). > > It should. Because this method does not know anything about 0x prefix > the whole string is invalid > to it. > Kernel.Integer KNOWS how to deal with prefixes, so it handles ocatal, > binary and hex representations > in string format just fine. > <...> > My question is why doesn't Float know how to deal with prefixes such as Hex? I wouldn't care if it tossed out invalid hex numbers such as 0x1h but it should at least try. As far as I am concerned the only difference between Float and Integer should be the return type, not what types they can handle. Integer has no problems with any valid Float or string representation of a Float, so Float should be able to handle any Integer or string representation of a valid Integer. I could probably create a different version of Float or to_f for my class that handles string values like 0x11 but would rather not as it may confuse someone in the future if they didn't know that it was different than the built-in methods. > Regards, > Rimantas > -- > http://rimantas.com/ >