God
God

Reputation: 684

How do I use regular expressions in Ruby?

I don't know how to implement regular expressions in Ruby. I tried this code, but it always returns true:

firstName = "Stepen123"
res = Validation_firstName(firstName)
puts res

def  Validation_firstName(firstName)
   reg = /[a-zA-z][^0-9]/
if reg.match(firstName)
   return true 
else
   return false
 end
 end

I am not sure what I did wrong.

Upvotes: 0

Views: 130

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

def validation_firstname(first_name)
  first_name.scan(/\d+/).empty?
end

p validation_firstname("Stepen123") #=> false
p validation_firstname("Stepen") #=> true

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160621

You can rewrite your method like this:

def validation_firstname(first_name)
  !!first_name[/^[a-z]+$/i]
end

Upvotes: 3

Related Questions