我用谷歌搜索了一个is_a?
函数来检查一个对象是否是一个整数。
但我尝试使用rails控制台,但它不起作用。
我运行了如下代码:
"1".is_a?
1.is_a?
我错过了什么吗?
答案 0 :(得分:19)
您忘记包含您正在测试的课程:
"1".is_a?(Integer) # false
1.is_a?(Integer) # true
答案 1 :(得分:3)
如果一个字符串实际上是一个整数,那么就没有一个内置函数可以说明,但你可以很容易地创建自己的函数:
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
,以避免暗示它应该返回true / false。]
答案 2 :(得分:1)
我使用正则表达式
if a =~ /\d+/
puts "y"
else
p 'w'
end
答案 3 :(得分:0)
Ruby有一个名为respond_to的函数?可用于查看特定类或对象是否具有具有特定名称的方法。语法类似于
User.respond_to?('name') # returns true is method name exists
otherwise false
http://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/
答案 4 :(得分:0)
也许这会对你有所帮助
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
答案 5 :(得分:0)
我想要类似的东西,但这些都没有为我做过,但是这个做了 - 用“class”:
a = 11
a.class
=> Fixnum