how to code a condition: 'can this string be converted into a date type'? (ruby)
can I code this condition in ruby somehow? I need to know if a string can be converted into a date variable. The only way how to do it is Date.parse("my string") and exception. Is there any other way?
date_scraped_from_the_net = "20 Dec 2009"开发者_StackOverflow社区 or it could be "today"
if date_scraped_from_the_net is not a date type
needs_to_be_updated = true
end
If you need sophisticated date parsing, I would try this.
However, if I understand your specific question, you'll want to use rescue
to use methods that raise errors in conditionals:
if (Date.parse(date_scraped_from_the_net) rescue nil)
needs_to_be_updated = true
end
精彩评论