Checking if a variable is an integer
You can use the is_a?
method
>> 1.is_a? Integer
=> true
>> "[email protected]".is_a? Integer
=> false
>> nil.is_a? Integer
=> false
If you want to know whether an object is an Integer
or something which can meaningfully be converted to an Integer (NOT including things like "hello"
, which to_i
will convert to 0
):
result = Integer(obj) rescue false
Use a regular expression on a string:
def is_numeric?(obj)
obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
If you want to check if a variable is of certain type, you can simply use kind_of?
:
1.kind_of? Integer #true
(1.5).kind_of? Float #true
is_numeric? "545" #true
is_numeric? "2aa" #false