Checking if a variable is an integer

后端 未结 11 1568
小鲜肉
小鲜肉 2020-12-07 16:20

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          


        
相关标签:
11条回答
  • 2020-12-07 16:47

    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

    0 讨论(0)
  • 2020-12-07 16:49

    You can use the is_a? method

    >> 1.is_a? Integer
    => true
    >> "dadadad@asdasd.net".is_a? Integer
    => false
    >> nil.is_a? Integer
    => false
    
    0 讨论(0)
  • 2020-12-07 16:53

    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
    
    0 讨论(0)
  • 2020-12-07 16:56

    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
    
    0 讨论(0)
  • 2020-12-07 16:56

    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.

    0 讨论(0)
提交回复
热议问题