Ruby密码复杂度验证问题:符号校验环节卡顿求助
Hey there! Let's figure out why your password validation code is getting stuck on the symbol check and fix it up properly.
First, let's break down the issues in your current code snippet that are causing the problem:
- The line
pass_clear = ()is a syntax error—you can't initialize a variable like that in Ruby. This alone would throw an error, but if you somehow got past it, thewhile pass_clear == nilloop logic is broken, leading to unexpected infinite loops. - Your symbol check was incomplete, which would either fail to trigger correctly or leave the loop running indefinitely.
Here's a fixed, fully functional version of your password validation code, with clear checks for all your requirements:
puts "Please enter your desired password: " valid_password = false # Loop until we get a valid password until valid_password password = gets.to_s.chomp.strip # Check each requirement one by one if password.length < 7 puts "Error: Your password must be at least 7 characters long." elsif password.count("a-z") == 0 puts "Error: Your password needs at least one lowercase letter (a-z)." elsif password.count("A-Z") == 0 puts "Error: Your password needs at least one uppercase letter (A-Z)." elsif password.count("0-9") == 0 puts "Error: Your password needs at least one number (0-9)." elsif password.count("^a-zA-Z0-9") == 0 puts "Error: Your password needs at least one symbol (e.g., !@#$%^&*)." else puts "Perfect! Your password meets all the requirements." valid_password = true end end
Key fixes and explanations:
- Replaced the broken
pass_clearsetup with a clear boolean flag (valid_password = false) and anuntilloop that runs until the password is valid—this makes the logic easy to follow. - Added
.stripto remove accidental leading/trailing spaces from the user's input, so we don't count whitespace towards the password length. - The symbol check uses
count("^a-zA-Z0-9")which counts any character that's not a letter or number—this covers all common symbols like!,@,#, etc. - Each failure case gives a specific error message, so the user knows exactly what to fix.
If you prefer a more concise approach, you can use a single regular expression to check all requirements at once:
puts "Please enter your desired password: " # Regex that enforces all your rules password_rules = /\A(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z0-9]).{7,}\z/ loop do password = gets.to_s.chomp.strip if password.match?(password_rules) puts "Success! Your password is valid." break else puts "Error: Password must be at least 7 characters, include a lowercase letter, uppercase letter, number, and symbol." end end
This regex breaks down to:
\A/\z: Match the entire string (no partial matches)(?=.*[a-z]): Ensure at least one lowercase letter(?=.*[A-Z]): Ensure at least one uppercase letter(?=.*\d): Ensure at least one number(?=.*[^a-zA-Z0-9]): Ensure at least one symbol.{7,}: Ensure minimum length of 7 characters
内容的提问来源于stack exchange,提问作者Rito
相关产品推荐
相关产品推荐

