Does Rails 3 or Ruby have a built-in way to check if a variable is an integer?
For example,
1.is_an_int #=> true
\"dadadad@asdasd.net\".is_an_int
Probably you are looking for something like this:
Accept "2.0 or 2.0 as an INT but reject 2.1 and "2.1"
num = 2.0
if num.is_a? String num = Float(num) rescue false end
new_num = Integer(num) rescue false
puts num
puts new_num
puts num == new_num
You can use the is_a?
method
>> 1.is_a? Integer
=> true
>> "dadadad@asdasd.net".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
There's var.is_a? Class
(in your case: var.is_a? Integer
); that might fit the bill. Or there's Integer(var)
, where it'll throw an exception if it can't parse it.