[英]Ruby test if input is integer
我有以下功能
def getValue(x)
puts "Key: #{x}"
if x =~ /[0-9]+/
puts "x is an int"
else
puts "x is a string"
end
end
在getValue(1)上,它應該輸出“ x is int”,但是我卻得到“ x is a string”
使用is_a?
檢查類型:
def getValue(x)
puts "Key: #{x}"
if x.is_a?(Integer)
puts "x is an int"
else
puts "x is a string"
end
end
輸出:
irb> getValue(1)
Key: 1
x is an int
irb> getValue("1")
Key: 1
x is a string
左側表達式必須是String
才能將=~
運算符與正則表達式一起使用。 在對正則表達式進行測試之前,在x
上調用to_s
:
def getValue(x)
puts "Key: #{x}"
if x.to_s =~ /[0-9]+/
puts "x is an int"
else
puts "x is a string"
end
end
另外,Ruby中的方法名稱是snake_case
,因此getValue
應該是get_value
。
或者您可以只使用x.is_a? Integer
如果要檢查值的類型 (而不是字符串表示形式) ,則為x.is_a? Integer
。
正則表達式建議:正如Michael Berkowski所提到的,您的正則表達式將匹配在任何地方都有數字的字符串。 您應該在\\A
(字符串的開頭)和\\Z
(字符串的結尾)之間定位模式:
\A[0-9]+\Z
更加挑剔: [0-9]
字符類等效於\\d
元字符,因此您也可以這樣做:
\A\d+\Z
您可能要測試是否可以將其轉換為整數,而不是是否為整數:
def get_value(x)
puts "Key: #{x}"
# This throws an ArgumentError exception if the value cannot be converted
Integer(x)
puts "x is an int"
rescue ArgumentError
puts "x is not an integer"
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.