题
我搜索过有一个 is_a?
功能可以检查对象是否是整数。
但是我尝试了Rails控制台,但行之有效。
我按以下方式运行代码:
"1".is_a?
1.is_a?
我错过了什么?
解决方案
没有内置的功能可以说字符串有效地是一个整数,但是您可以轻松地制作自己的功能:
class String
def int
Integer(self) rescue nil
end
end
这是因为内核法 Integer()
如果无法将字符串转换为整数,则会引发错误 rescue 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
为了避免暗示它应该仅返回true/fals。]
其他提示
您忘了包括您正在测试的课程:
"1".is_a?(Integer) # false
1.is_a?(Integer) # true
我使用了正则表达式
if a =~ /\d+/
puts "y"
else
p 'w'
end
Ruby具有称为rection_to的功能?可以用来查看特定类或对象是否具有具有特定名称的方法。语法就像
User.respond_to?('name') # returns true is method name exists
otherwise false
也许这会帮助您
str = "1"
=> "1"
num = str.to_i
=> 1
num.is_a?(Integer)
=> true
str1 = 'Hello'
=> "Hello"
num1 = str1.to_i
=> 0
num1.is_a?(Integer)
=> true
我想要类似的东西,但是这些都不是为我做的,但是这确实 - 使用“ class”:
a = 11
a.class
=> Fixnum
不隶属于 StackOverflow