Reputation: 38842
I would like to check if a variable's string value is a number string (e.g. '3.2', '1') or alphabet string (e.g. 'abc'), is there any easy way to do this in ruby or Rails 3 ?
Upvotes: 0
Views: 418
Reputation: 2647
I would use Float().
def numeric?(object)
true if Float(object) rescue false
end
Upvotes: 7
Reputation: 15605
Implementations using Kernel#Float
expect and rescue an exception, which is slow and poor design. I would prefer:
class String
def is_numeric?
string.to_f.to_s == string ||
string.to_i.to_s == string
end
end
Upvotes: 0
Reputation: 6986
You could use regular expressions to help you with this.
str = "abc"
# first regex checks for character string, second regex checks for floating point number
if not str.empty? and str =~ /^[a-z]+$/i or str =~ /^[-+]?[0-9]*\.?[0-9]*$/ then
# this is a match
else
# no match
end
I didn't fully test these regexes - you'd have to make sure these fit your needs.
Upvotes: 1
Reputation: 239270
You could add a is_numeric?
method to the string class:
class String
def is_numeric?
true if Float(self) rescue false
end
end
p "123".is_numeric? # true
p "abc".is_numeric? # false
Using Float()
instead of a regular expression handles some weird cases that you might not want to consider "numeric", like +123
or -.3
.
Upvotes: 1