Stefano Crocco
11/22/2007 5:50:00 PM
Alle gioved=C3=AC 22 novembre 2007, Peter Bunyan ha scritto:
> I'm working on an RPN calculator (don't ask why...) and I'm having
> trouble getting a number from gets - how am I supposed to know whether
> it's a number?
>
> At the moment I'm doing [eval(oper) =3D=3D oper.to_f], which is far from
> ideal. Any ideas? You all get to win my calculator if you know of a
> better way :D.
Do you mean you need to find out whether a string contains a number or not?=
In=20
this case, you can either use Kernel#Float, which returns str.to_f if the=20
string contains a number and raises an exception owtherwise, or try to craf=
t=20
a regexp which only matches strings containing numbers. For example, the=20
(untested) regexp
/[+-]?\d+(.\d+)?(e[+-]?\d+)?/
should match numbers with an optional + or - in front, followed by at least=
=20
one digit, with an optional decimal part (if there's a dot, there should be=
=20
at least one digit following it; if you want to allow something like 11. th=
en=20
replace (.\d+) with (.\d*) ). The number can also be in exponential form,=20
with a downcase e and an optional + or - in front of the exponent.
I hope this helps
Stefano