How to check if a variable is a number or a string in Ruby?
class Object
def is_number?
to_f.to_s == to_s || to_i.to_s == 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
var.is_a? String
var.is_a? Numeric
There are several ways:
>> 1.class #=> Fixnum
>> "foo".class #=> String
>> 1.is_a? Numeric #=> true
>> "foo".is_a? String #=> true
if chr.to_i != 0
puts "It is number, yep"
end
Print its class, it will show you which type of variable is (e.g. String or Number).
e.g.:
puts varName.class
class Object
def numeric?
Float(self) != nil rescue false
end
end