没有内置函数可以判断字符串是否有效地是整数,但您可以轻松地制作自己的:
class String
def int
Integer(self) rescue nil
end
end
这是可行的,因为如果字符串无法转换为整数,内核方法 Integer() 会引发错误,而内联 rescue nil 会将该错误变为 nil。
Integer("1") -> 1
Integer("1x") -> nil
Integer("x") -> nil
因此:
"1".int -> 1 (which in boolean terms is `true`)
"1x".int -> nil
"x".int -> nil
您可以更改函数以在真实情况下返回true,而不是整数本身,但是如果您正在测试字符串以查看它是否为整数,那么您很可能想要使用该整数来做一些事情!我经常做这样的事情:
if i = str.int
# do stuff with the integer i
else
# error handling for non-integer strings
end
虽然如果测试职位的作业冒犯了你,你总是可以这样做:
i = str.int
if i
# do stuff with the integer i
else
# error handling for non-integer strings
end
无论哪种方式,这种方法都只进行一次转换,如果你必须做很多,这可能是一个显着的速度优势。
[将函数名称从 int? 更改为 int 以避免暗示它应该只返回真/假。]