xin buxu1
xin buxu1

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

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

Answers (3)

steenslag
steenslag

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

Brian Davis
Brian Davis

Reputation: 357

Are you looking for a regular expression?

>> 'abc.' =~ /[a-zA-Z]/
=> 0
>> 'abc.' =~ /[0-9]/
=> nil

Upvotes: 1

umezo
umezo

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-Zcharacters.

You can use http://rubular.com/ to try different regular expressions.

Upvotes: 2

Related Questions