我可以用 ruby 编写这个条件吗?我需要知道字符串是否可以转换为日期变量。唯一的方法是 Date.parse("my string") 和异常。还有其他办法吗?
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
最佳答案
如果您需要复杂的日期解析,我会尝试 this .
但是,如果我理解您的具体问题,您将需要使用 rescue
来使用在条件中引发错误的方法:
if (Date.parse(date_scraped_from_the_net) rescue nil)
needs_to_be_updated = true
end
关于ruby - 如何编写条件 : 'can this string be converted into a date type' ? (ruby),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130542/