How to check if a variable is a number or a string?

How to check if a variable is a number or a string in Ruby?

+51
ruby
Dec 23 '11 at 12:56 on
source share
7 answers

There are several ways:

>> 1.class #=> Fixnum >> "foo".class #=> String >> 1.is_a? Numeric #=> true >> "foo".is_a? String #=> true 
+72
Dec 23 '11 at 12:58
source share
 class Object def is_number? self.to_f.to_s == self.to_s || self.to_i.to_s == self.to_s end end > 15.is_number? => true > 15.0.is_number? => true > '15'.is_number? => true > '15.0'.is_number? => true > 'String'.is_number? => false 
+25
May 9 '13 at 7:35
source share
 var.is_a? String var.is_a? Numeric 
+11
Dec 23 '11 at 12:58
source share

finishing_moves stone includes String#numeric? a method to accomplish this very task. The approach is the same as the installero answer, just packaged.

 "1.2".numeric? #=> true "1.2e34".numeric? #=> true "1.2.3".numeric? #=> false "a".numeric? #=> false 
+5
May 26 '16 at 14:25
source share

Print out your class, it will show you what type of variable (e.g. String or Number).

eg:.

 puts varName.class 
+2
Dec 23 '11 at 12:58
source share
 class Object def numeric? Float(self) != nil rescue false end end 
0
Dec 21 '18 at 22:09
source share
 if chr.to_i != 0 puts "It is number, yep" end 
-2
Apr 6 '17 at 3:33 on
source share



All Articles