Ruby中如何实现Ticket类的date=方法校验yyyy-mm-dd日期格式?
date= Method Hey there! Let's work through this date validation problem for your Ticket class. The key here is to check both the format of the input string and whether it represents a valid calendar date—here's how to do it properly:
Step-by-Step Implementation
First, we'll use a regular expression to enforce the yyyy-mm-dd format, then validate that the date actually exists (since something like 2023-02-30 fits the format but isn't a real date). We'll also make sure the method behaves exactly as your example shows.
require 'date' class Ticket def date=(input_date) # Regex matches strings exactly in yyyy-mm-dd format valid_format = input_date.match?(/^\d{4}-\d{2}-\d{2}$/) if valid_format begin # Attempt to parse the date to confirm it's a real calendar date Date.parse(input_date) # If parsing succeeds, store and return the valid date @date = input_date rescue ArgumentError # Invalid date (e.g., 2023-02-30) triggers this error "Please submit the date in the format 'yyyy-mm-dd'." end else # Format doesn't match yyyy-mm-dd "Please submit the date in the format 'yyyy-mm-dd'." end end # Optional: Add a getter method to retrieve the stored date def date @date end end
How This Works
- Regex Format Check: The regex
/^\d{4}-\d{2}-\d{2}$/ensures the input starts with 4 digits (year), followed by a hyphen, 2 digits (month), another hyphen, and 2 digits (day)—no extra characters allowed. - Date Validity Check: Using
Date.parse(from Ruby's built-indatelibrary) ensures the date is actually valid. For example,2023-02-30will throw anArgumentErrorbecause February never has 30 days. - Return Behavior: If everything checks out, we store the date in an instance variable and return the valid string. If either the format is wrong or the date is invalid, we return your specified error message.
Testing the Implementation
Let's verify it matches your examples:
ticket = Ticket.new puts ticket.date = "2013-11-12" # Output: "2013-11-12" puts ticket.date = "13-11-12" # Output: "Please submit the date in the format 'yyyy-mm-dd'." puts ticket.date = "2023-02-30" # Output: "Please submit the date in the format 'yyyy-mm-dd'."
Quick Note on strftime
You mentioned wondering about strftime—that method is used to convert existing Date or Time objects into formatted strings. Since we're starting with a string input, it doesn't help with validation directly. However, if you wanted to ensure the stored date is always returned in yyyy-mm-dd format (even if someone passes a valid date object instead of a string), you could adjust the getter to use it:
def date @date ? Date.parse(@date).strftime("%Y-%m-%d") : nil end
But for your specific problem, the initial implementation is perfect.
内容的提问来源于stack exchange,提问作者newkidontheblock

