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

The Best and Simple way is using Float

val = Float "234" rescue nil

Float "234" rescue nil #=> 234.0

Float "abc" rescue nil #=> nil

Float "234abc" rescue nil #=> nil

Float nil rescue nil #=> nil

Float "" rescue nil #=> nil

Integer is also good but it will return 0 for Integer nil

查看更多
大哥的爱人
3楼-- · 2019-01-01 11:02

A much simpler way could be

/(\D+)/.match('1221').nil? #=> true
/(\D+)/.match('1a221').nil? #=> false
/(\D+)/.match('01221').nil? #=> true
查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 11:03

Might not be suitable for all cases but a simple

"12".to_i   => 12
"blah".to_i => 0

might also do for some.

So if it's a number and not 0 it will return a number. If it returns 0 it's either a word string or 0.

查看更多
闭嘴吧你
5楼-- · 2019-01-01 11:03

Although explicit use of the case equality operator should be avoided, Regexp#=== looks very clean here:

def integer?(str)
  /\A[+-]?\d+\z/ === str
end

integer? "123"    # true
integer? "-123"   # true
integer? "+123"   # true

integer? "a123"   # false
integer? "123b"   # false
integer? "1\n2"   # false
查看更多
裙下三千臣
6楼-- · 2019-01-01 11:04

You can do a one liner:

str = ...
int = Integer(str) rescue nil

if int
  int.times {|i| p i}
end

or even

int = Integer(str) rescue false

Depending on what you are trying to do you can also directly use a begin end block with rescue clause:

begin
  str = ...
  i = Integer(str)

  i.times do |j|
    puts j
  end
rescue ArgumentError
  puts "Not an int, doing something else"
end
查看更多
与君花间醉酒
7楼-- · 2019-01-01 11:04

Solution:

# /initializers/string.rb
class String
  IntegerRegex = /^(\d)+$/

  def integer?
    !!self.match(IntegerRegex)
  end
end

# any_model_or_controller.rb
'12345'.integer? # true
'asd34'.integer? # false

Explanation:

  • /^(\d)+$/is regex expression for finding digits in any string. You can test your regex expressions and results at http://rubular.com/.
  • We save it in a constant IntegerRegex to avoid unnecessary memory allocation everytime we use it in the method.
  • integer? is an interrogative method which should return true or false.
  • match is a method on string which matches the occurrences as per the given regex expression in argument and return the matched values or nil.
  • !! converts the result of match method into equivalent boolean.
  • And declaring the method in existing String class is monkey patching, which doesn't change anything in existing String functionalities, but just adds another method named integer? on any String object.
查看更多
登录 后发表回答