M
Michael W. Ryder
In my continuing work learning Ruby while creating a Rational class I
ran into a problem with converting Strings. I am allowing Strings as
input to the .new method and converting them to a Float, Integer, or
Rational before continuing. At first I was just using Float(x) and
later converting the Float to an Integer. This works fine unless I try
something like Float("0x11") which crashes. Integer("0x11") returns 17
as expected. Currently I have to try to convert to Float and if that
fails try to convert to Integer which seems to be more work than it
needs to be.
If I use Float("17") it returns 17.0 and Float(0x11) returns 17.0, both
as expected. Why doesn't Float("0x11") work? 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").
Part of what I am doing is trying to follow the statement in Pickaxe
about duck typing and programming for any input, not just a select subset.
ran into a problem with converting Strings. I am allowing Strings as
input to the .new method and converting them to a Float, Integer, or
Rational before continuing. At first I was just using Float(x) and
later converting the Float to an Integer. This works fine unless I try
something like Float("0x11") which crashes. Integer("0x11") returns 17
as expected. Currently I have to try to convert to Float and if that
fails try to convert to Integer which seems to be more work than it
needs to be.
If I use Float("17") it returns 17.0 and Float(0x11) returns 17.0, both
as expected. Why doesn't Float("0x11") work? 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").
Part of what I am doing is trying to follow the statement in Pickaxe
about duck typing and programming for any input, not just a select subset.