如何编写条件:'可以将此字符串转换为日期类型'吗?(红宝石)

Rad*_*dek 2 ruby date

我可以用某种方式在ruby中编码这个条件吗?我需要知道字符串是否可以转换为日期变量.唯一的方法是Date.parse("我的字符串")和异常.还有其他方法吗?

date_scraped_from_the_net = "20 Dec 2009" or it could be "today"

if date_scraped_from_the_net is not a date type 
  needs_to_be_updated = true
end
Run Code Online (Sandbox Code Playgroud)

tfw*_*ght 5

如果你需要复杂的日期解析,我会尝试这个.

但是,如果我理解您的具体问题,您将需要使用rescue在条件中引发错误的方法:

if (Date.parse(date_scraped_from_the_net) rescue nil)
  needs_to_be_updated = true
end
Run Code Online (Sandbox Code Playgroud)