Checking if a variable is an integer

后端 未结 11 1574
小鲜肉
小鲜肉 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:39

    If you're uncertain of the type of the variable (it could be a string of number characters), say it was a credit card number passed into the params, so it would originally be a string but you want to make sure it doesn't have any letter characters in it, I would use this method:

        def is_number?(obj)
            obj.to_s == obj.to_i.to_s
        end
    
        is_number? "123fh" # false
        is_number? "12345" # true
    

    @Benny points out an oversight of this method, keep this in mind:

    is_number? "01" # false. oops!
    

提交回复
热议问题