Ruby CLI程序中使用正则验证五位Zipcode的实现需求
Solution for Validating 5-Digit Zip Codes in Your Ruby CLI
Got it, let's get your zip code validation sorted out for your movie theater scraper CLI. Since you just need to validate the format (not whether the zip code actually exists), a simple regular expression is perfect here—no external gems required.
Step 1: The Right Regular Expression
Use this regex to match exactly 5 digits, with no extra characters before or after:
/\A\d{5}\z/
\Aanchors the match to the start of the string (avoids leading spaces/characters)\d{5}matches exactly 5 numeric digits\zanchors the match to the end of the string (avoids trailing spaces/characters)
This is better than checking a numeric range because it preserves leading zeros (like00001), which are valid for some US zip codes.
Step 2: Update Your program_input Method
Here's the revised code with the validation, plus the lowercase handling for "exit" that you mentioned:
def program_input input = gets.chomp.downcase # Handle exit/Exit/EXIT and remove newline if input == "exit" puts "Enjoy your movie!" elsif input.match?(/\A\d{5}\z/) # Validate 5-digit zip code format sleep(0.5) print "Calculating" 3.times do sleep(0.25) print "." end puts # Add a newline after the dots zip_code = input scraper = Scraper.new(zip_code) # Add logic here to use the scraper (e.g., display theaters/movies) else # Handle invalid input by prompting the user again puts "Oops, that's not a valid input. Please enter a 5-digit zip code or 'exit'." program_input # Recursively call the method to get new input end end
Key Improvements:
gets.chomp.downcaseensures "exit" is recognized regardless of capitalization, and removes any trailing newline characters.match?is a clean, efficient way to check if the input matches the regex (returns a boolean).- Added an
elsebranch to handle invalid inputs (like 4 digits, letters, or random text) and prompt the user again. - Replaced the repeated
sleep/printwith a loop to make the code cleaner.
This will ensure only valid 5-digit zip codes are passed to your scraper, and the program behaves as expected when the user wants to exit.
内容的提问来源于stack exchange,提问作者Levi Borland
相关产品推荐
相关产品推荐

