You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何实现Ticket类的date=方法校验yyyy-mm-dd日期格式?

Implementing Date Validation for the Ticket Class's 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-in date library) ensures the date is actually valid. For example, 2023-02-30 will throw an ArgumentError because 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:28:15