Checking if a variable is an integer

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

    I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.

    if column.class < Numeric
      number_to_currency(column)
    else
      column.html_safe
    end
    

    In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex

提交回复
热议问题