0

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.

3
  • 2
    Your regex matches a single letter followed by something that is not a digit, so it matched the beginning of your string, specifically "St". What are you trying to match, anyway? Commented May 9, 2013 at 5:23
  • Go to rubular.com/r/59cqVn4YPs and use it to see how your pattern works. Commented May 9, 2013 at 5:26
  • thank you, i have to match if firstName should have only "Stepen" not "Stepen123", simply "Stepen" returns true, "stepen123" returns false Commented May 9, 2013 at 5:27

2 Answers 2

3

You can rewrite your method like this:

def validation_firstname(first_name)
  !!first_name[/^[a-z]+$/i]
end
Sign up to request clarification or add additional context in comments.

3 Comments

really thankYou its working, i have tried /^[a-zA-Z]$/ this. i havent put "+". whats the meaning for this "+"
@God: It means "one or more." So one or more characters in the set [a-zA-Z]. Without that, it will only match one-character strings.
That is going to be for you to figure out. There are all sorts of regular expression tutorials on the internet, along with the cheat-sheet at the bottom of the page at Rubular.com. I'll just say that without it your code won't work and you should use what I gave in my example, rather than leave out things you don't understand.
1
def validation_firstname(first_name)
  first_name.scan(/\d+/).empty?
end

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

1 Comment

This will return true for the input " ", which I don't think is desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.