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:12

One liner in string.rb

def is_integer?; true if Integer(self) rescue false end
查看更多
旧时光的记忆
3楼-- · 2019-01-01 11:14
  def isint(str)
    return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
  end
查看更多
与风俱净
4楼-- · 2019-01-01 11:16
class String
  def integer?
    Integer(self)
    return true
  rescue ArgumentError
    return false
  end
end
  1. It isn't prefixed with is_. I find that silly on questionmark methods, I like "04".integer? a lot better than "foo".is_integer?.
  2. It uses the sensible solution by sepp2k, which passes for "01" and such.
  3. Object oriented, yay.
查看更多
查无此人
5楼-- · 2019-01-01 11:21

For more generalised cases (including numbers with decimal point), you can try the following method:

def number?(obj)
  obj = obj.to_s unless obj.is_a? String
  /\A[+-]?\d+(\.[\d]+)?\z/.match(obj)
end

You can test this method in an irb session:

(irb)
>> number?(7)
=> #<MatchData "7" 1:nil>
>> !!number?(7)
=> true
>> number?(-Math::PI)
=> #<MatchData "-3.141592653589793" 1:".141592653589793">
>> !!number?(-Math::PI)
=> true
>> number?('hello world')
=> nil
>> !!number?('hello world')
=> false

For a detailed explanation of the regex involved here, check out this blog article :)

查看更多
何处买醉
6楼-- · 2019-01-01 11:21

Expanding on @rado's answer above one could also use a ternary statement to force the return of true or false booleans without the use of double bangs. Granted, the double logical negation version is more terse, but probably harder to read for newcomers (like me).

class String
  def is_i?
     self =~ /\A[-+]?[0-9]+\z/ ? true : false
  end
end
查看更多
浮光初槿花落
7楼-- · 2019-01-01 11:24

personally I like the exception approach although I would make it a little terser.

class String
  def integer?(str)
    !!Integer(str) rescue false
  end
end

However as others have already stated this doesn't work with Octal strings...

查看更多
登录 后发表回答