Here are some suggestions for improving your method. Normally I would make it with a comment, but formatting restrictions make that impractical in this case. Consider writing it like this:
SPECIAL_CHARS = '!@#$%&*+:?'
def check_password(password)
"Your pw does not work because " +
case
when password.length < 6
"it is too short"
when password.match(/[A-Z]/).nil?
"it does not contain a capital letter"
when password.match(/\d|[{SPECIAL_CHARS}]/).nil?
"it needs either a digit or special char"
else
return "Valid Password!"
end
end
check_password("abcde")
#=> "Your pw does not work because it is too short"
check_password("abcdef")
#=> "Your pw does not work because it does not contain a capital letter"
check_password("abcdeF")
#=> "Your pw does not work because it needs either a digit or special char"
check_password("abcdeF@")
#=> "Valid Password!"
check_password("abcdeF1")
#=> "Valid Password!"
I removed
when password.index(/([!,@,#,$,%,&,*,+,:,?\w])/) > 0
"nope. !,@,#,$,%,&,*,+,:,? are the only special characters available"
because I didn't understand what it was checking for.
Notice that there is only one return
, and that is when the password is valid. If the password is not valid, the result of the case
statement (a string) is added to the string, "Your pw does not work because "
and returned (since it would be the last statement executed by the method--no return
needed).
I replaced index
with match
, though you could alternatively write:
when !(password =~ /[A-Z]/)
or
when !password[/[A-Z]/]