From: Brian Candler Date: 2010-07-12T05:53:34+09:00 Subject: Re: Basic Question: How do you check to see if gets is a number? Rick Denatale wrote: > On Sun, Jul 11, 2010 at 12:34 PM, Adam Bourg > wrote: >> if ( age.to_f.to_s == true ) > > This will NEVER happen. > > age.to_f converts the string to a float. If the string isn't valid it > returns 0.0. I'd use Float(age), which will raise an exception for invalid values. irb(main):001:0> Float("1") => 1.0 irb(main):002:0> Float("1.5") => 1.5 irb(main):003:0> Float("1.5 ") => 1.5 irb(main):004:0> Float("1.5 z") ArgumentError: invalid value for Float(): "1.5 z" from (irb):4:in `Float' from (irb):4 from :0 > Now I'm not sure whether or not you really want to accept an age as a > float, or just an integer, but you need to do something else to > validate the string. > > One way would be to use a regular expression, e.g. something like > > if age =~ /^d+$/ # for an integer except that particular regexp allows strings which are not just numbers, e.g. >> age = "foo\n123\nbar" => "foo\n123\nbar" >> puts "oops" if age =~ /^\d+$/ oops => nil Use \A and \z to match start and end of the string. > or > if age =~/^d+(|\.\d*)$/ # for a float except that particular regexp allows invalid floats (e.g. "1.") and disallows valid ones (e.g. "1.0e5") Using regexps to validate data is perfectly reasonable, just be very careful that the regexp you write matches exactly what you expect and nothing else. > Or use either Kernel#Integer or Kernel#Float which raise an error if > they don't like the string: > > float_age = Float(age) rescue nil > if float_age > #.... Beware that Integer() handles values which start with zero as octal. >> "0100".to_i => 100 >> Integer("0100") => 64 -- Posted via http://www.ruby-forum.com/.