Possible Duplicate:
Test if string is a number in Ruby on Rails
Currently I have this (awful) code:
def is_num(num_given)
begin
num_given.to_i
worked = true
rescue
worked = false
ensure
return worked
end
end
Which I refactored to this:
def is_num(num_given)
num_given.to_i.is_a?(Numeric) rescue false
end
This still just doesn’t feel right to me, is there a better way to do this?
Both of these implementations work fine for my purposes, I am just looking for some code euphoria.
The functions you listed won’t work:
The problem is that they don’t raise an error for invalid input. What you want is
Integer, which will raise an error which you can rescue:This works:
(There may be a more natural way to do this, though.)