How to test if a string is basically an integer in quotes using Ruby

Well, here’s the easy way:

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

>> "12".is_integer?
=> true
>> "blah".is_integer?
=> false

I don’t agree with the solutions that provoke an exception to convert the string – exceptions are not control flow, and you might as well do it the right way. That said, my solution above doesn’t deal with non-base-10 integers. So here’s the way to do with without resorting to exceptions:

  class String
    def integer? 
      [                          # In descending order of likeliness:
        /^[-+]?[1-9]([0-9]*)?$/, # decimal
        /^0[0-7]+$/,             # octal
        /^0x[0-9A-Fa-f]+$/,      # hexadecimal
        /^0b[01]+$/              # binary
      ].each do |match_pattern|
        return true if self =~ match_pattern
      end
      return false
    end
  end

Leave a Comment