Checking if a variable is an integer

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

    In case you don't need to convert zero values, I find the methods to_i and to_f to be extremely useful since they will convert the string to either a zero value (if not convertible or zero) or the actual Integer or Float value.

    "0014.56".to_i # => 14
    "0014.56".to_f # => 14.56
    "0.0".to_f # => 0.0
    "not_an_int".to_f # 0
    "not_a_float".to_f # 0.0
    
    "0014.56".to_f ? "I'm a float" : "I'm not a float or the 0.0 float" 
    # => I'm a float
    "not a float" ? "I'm a float" : "I'm not a float or the 0.0 float" 
    # => "I'm not a float or the 0.0 float"
    

    EDIT2 : be careful, the 0 integer value is not falsey it's truthy (!!0 #=> true) (thanks @prettycoder)

    EDIT

    Ah just found out about the dark cases... seems to only happen if the number is in first position though

    "12blah".to_i => 12
    

提交回复
热议问题