Reputation: 407
how to check a string is valid in ruby? A valid string will be only including either character or digital number OR both. This is what I have tried:
str = "abc."
str[3].is_a? Numeric
str[3].is_a? String
"." here is also string (since ruby doesn't have char), but in my definition of valid string, "abc." is invalid. Is there any method in ruby to check isLetter and isDigital like java does?
Upvotes: 2
Views: 2910
Reputation: 80065
Regex: (Note if underscores are acceptable chars then /\W/
is usable).
def valid?(str)
(str =~ /[^a-zA-Z0-9]/).nil?
end
p valid? "123" # => true
p valid? "123$" # => false
No Regex:
def valid?(str)
str.count("a-zA-Z0-9") == str.size
end
p valid? "123" # => true
p valid? "123$" # => false
Upvotes: 2
Reputation: 357
Are you looking for a regular expression?
>> 'abc.' =~ /[a-zA-Z]/
=> 0
>> 'abc.' =~ /[0-9]/
=> nil
Upvotes: 1
Reputation: 1579
You're on the right track. You'll just want to use a regular expression to figure out which characters to accept/reject.
something like this would accept all lowercase and uppercase alphabet characters.
str = 'abc.'
str[/([a-zA-Z]+)/]
This works because the regular expression ([a-zA-Z]+)
matches a group ()
of one or more +
characters with lowercase a-z
or uppercase A-Z
characters.
You can use http://rubular.com/ to try different regular expressions.
Upvotes: 2