From: linas Date: 2002-01-16T07:33:58+09:00 Subject: Re: I/O gets and integers thanks, that helps. -linas On Sat, 12 Jan 2002, Mathieu Bouchard wrote: > > On Sun, 13 Jan 2002, linas wrote: > > Whenever i use gets to retireve user input, it always retrieves it as a > > string. Is there anyway that it can be retireved as an integer (or real > > number)? > > There's no method that does exactly that, because instead you combine gets > with a method that does the kind of conversion you want. You see, the > number could be written in different numbering systems (2,8,10,16,64), > with or without a prefix, etc. > > You can use Integer(gets) to get an integer written Ruby-style (decimal > integers not starting with zero; zero reserved to indicate other numbering > systems). > > You can use Float(gets) to get a floating-point number. This is called a > "Real" number in Pascal, but this is extremely misleading: all it is is > scientific notation with a fixed number of digits no matter how big the > number is. > > If you want to accept both Integers and Floats, you can do > this: (temp=gets; Integer(temp) rescue Float(temp)) but there is a gotcha > when mixing integers and floats carelessly (integer divided by integer > gives an integer), so if you want you can append .to_f to that to make > sure every result is a Float even when it was written as an Integer. > > ________________________________________________________________ > Mathieu Bouchard http://hostname.2y.net/~matju > > > > >