Checking if a variable is an integer

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

    To capitalize on the answer of Alex D, using refinements:

    module CoreExtensions
      module Integerable
        refine String do
          def integer?
            Integer(self)
          rescue ArgumentError
            false
          else
            true
          end
        end
      end
    end
    

    Later, in you class:

    require 'core_ext/string/integerable'
    
    class MyClass
      using CoreExtensions::Integerable
    
      def method
        'my_string'.integer?
      end
    end
    

提交回复
热议问题