Test if a string is basically an integer in quotes

2019-01-01 10:30发布

I need a function, is_an_integer, where

"12".is_an_integer? returns true
"blah".is_an_integer? returns false

how can i do this in ruby? i would write a regex but im assuming there is a helper for this that i am not aware of

标签: ruby
19条回答
忆尘夕之涩
2楼-- · 2019-01-01 11:06
"12".match(/^(\d)+$/)      # true
"1.2".match(/^(\d)+$/)     # false
"dfs2".match(/^(\d)+$/)    # false
"13422".match(/^(\d)+$/)   # true
查看更多
春风洒进眼中
3楼-- · 2019-01-01 11:09

You can use Integer(str) and see if it raises:

def is_num?(str)
  !!Integer(str, 10)
rescue ArgumentError, TypeError
  false
end

Addendum: It should be pointed out that while this does return true for "01", it does not for "09", simply because 09 would not be a valid integer literal.

Addendum to addendum: Fixed this by changing Integer(str) to Integer(str, 10), as per @jason-axelson's comment.

查看更多
谁念西风独自凉
4楼-- · 2019-01-01 11:10

you can use is_a? method. for eg. 1.is_a? Integer will return true

查看更多
十年一品温如言
5楼-- · 2019-01-01 11:11

You can use regular expressions. Here is the function with @janm's suggestions.

class String
    def is_i?
       !!(self =~ /\A[-+]?[0-9]+\z/)
    end
end

An edited version according to comment from @wich:

class String
    def is_i?
       /\A[-+]?\d+\z/ === self
    end
end

In case you only need to check positive numbers

  if !/\A\d+\z/.match(string_to_check)
      #Is not a positive number
  else
      #Is all good ..continue
  end  
查看更多
心情的温度
6楼-- · 2019-01-01 11:11

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

EDIT: 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
查看更多
长期被迫恋爱
7楼-- · 2019-01-01 11:12

I prefer:

config/initializers/string.rb

class String
  def number?
    Integer(self).is_a?(Integer)
  rescue ArgumentError, TypeError
    false
  end
end

and then:

[218] pry(main)> "123123123".number?
=> true
[220] pry(main)> "123 123 123".gsub(/ /, '').number?
=> true
[222] pry(main)> "123 123 123".number?
=> false

or check phone number:

"+34 123 456 789 2".gsub(/ /, '').number?
查看更多
登录 后发表回答