I have the following function
def getValue(x)
puts "Key: #{x}"
if x =~ /[0-9]+/
puts "x is an int"
else
puts "x is a string"
end
end
On getValue(1) it should output "x is an int" but instead I get "x is a string"
The left-hand expression must be a String to use the =~ operator with a regular expression. Call to_s on x before testing against the regular expression:
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
Also, method names in Ruby are snake_case, so getValue should be get_value.
Or you could just use x.is_a? Integer if you want to check the type of the value, not the string representation.
Regex advise: As Michael Berkowski mentioned, your regular expression will match a string that has a digit anywhere. You should anchor the pattern between \A (start of string) and \Z (end of string):
\A[0-9]+\Z
Even more nit-picking: the [0-9] character class is equivalent to the \d meta character, so you could do this as well:
\A\d+\Z
^$ because it would also match notanumber99notanumber as /[0-9]+/Use is_a? to inspect the type:
def getValue(x)
puts "Key: #{x}"
if x.is_a?(Integer)
puts "x is an int"
else
puts "x is a string"
end
end
Output:
irb> getValue(1)
Key: 1
x is an int
irb> getValue("1")
Key: 1
x is a string
puts x.class = #{x.class}"?case x; when Fixnum then process_fixnum(x); when String then process_string(x); when Float... end.