我正在尝试使用正则表达式并在ruby中测试我自己的代码。使用下面的例子,我预计最终的回报会返回true,但事实并非如此。但是,check_password方法会返回"你的pw不起作用,因为它太短了#34;为什么真/假检查不返回true?
def err_message(reason)
puts "Your pw does not work because " + reason
end
def check_password(password)
if password.length<6
return err_message("it is too short")
elsif password.index(/[A-Z]/)==nil
return err_message("it does not contain a capital letter")
elsif password.index(/\d|[!,@,#,$,%,&,*,+,:,?]/)==nil
return err_message("it needs either a digit or special character")
elsif password.index(/([!,@,#,$,%,&,*,+,:,?\w])/)>0
return err_message("nope. !,@,#,$,%,&,*,+,:,? are the only special characters available")
else
return "Valid Password!"
end
end
puts check_password("aaaaa")=="Your pw does not work because it is too short"
答案 0 :(得分:2)
err_message
将评估puts "Your pw does not work because " + reason
并返回nil
,因为nil
是puts
的返回值,将方法定义更改为如下所示:
def err_message(reason)
"Your pw does not work because " + reason
end
然后:
puts check_password("aaaaa")=="Your pw does not work because it is too short"
# => true
答案 1 :(得分:0)
以下是一些改进方法的建议。通常我会用评论来表达,但格式限制使得在这种情况下不切实际。考虑这样写:
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!"
我删除了
when password.index(/([!,@,#,$,%,&,*,+,:,?\w])/) > 0
"nope. !,@,#,$,%,&,*,+,:,? are the only special characters available"
因为我不明白它正在检查什么。
请注意,只有一个return
,即密码有效时。如果密码无效,则case
语句(字符串)的结果将添加到字符串"Your pw does not work because "
并返回(因为它将是该方法执行的最后一个语句 - 否{需要{1}}。
我将return
替换为index
,但您也可以写:
match
或
when !(password =~ /[A-Z]/)