如何使用Ruby测试字符串是否基本上是引号中的整数 [英] How to test if a string is basically an integer in quotes using Ruby
本文介绍了如何使用Ruby测试字符串是否基本上是引号中的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个函数,is_an_integer
,其中
I need a function, is_an_integer
, where
"12".is_an_integer?
返回 true."blah".is_an_integer?
返回 false.
"12".is_an_integer?
returns true."blah".is_an_integer?
returns false.
我怎样才能在 Ruby 中做到这一点?我会写一个正则表达式,但我假设有一个我不知道的帮手.
How can I do this in Ruby? I would write a regex but I'm assuming there is a helper for this that I am not aware of.
推荐答案
您可以使用正则表达式.这是带有@janm 建议的函数.
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
根据@wich 的评论编辑的版本:
An edited version according to comment from @wich:
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
如果你只需要检查正数
if !/\A\d+\z/.match(string_to_check)
#Is not a positive number
else
#Is all good ..continue
end
这篇关于如何使用Ruby测试字符串是否基本上是引号中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文