问题描述
|
当我在irb中运行这三行时
date=\"02 Jul 2008,08:41\"
d=Date.strptime(date,\"%d %b %Y,%H:%M\").iso8601
Time.parse(d).utc.iso8601
output=>\"2008-07-01T18:30:00Z\"
但是,如果在没有这些行的情况下可以正常工作的循环中使用,则在生成第一步的输出后,循环将中断。
生成日期值的代码被标记为nil
示例代码如下
page_doc = page_doc.xpath(\'//div[@id=\"page-body\"]\').first
page_doc.xpath(\'./div\').each do |div|
author_node=div.xpath(\'.//p[@class=\"author\"]/strong/a\').first
if author_node == nil
author = \"NA\"
else
author = author_node.content.chomp.strip.gsub(\"Gjest:\",\"\")
end
author_url_node = div.xpath(\'.//p[@class=\"author\"]/strong/a/@href\').first
if author_url_node == nil
author_url = \"NA\"
else
author_url = @site + author_url_node.content.chomp.strip
end
date_node = div.xpath(\'.//p[@class=\"author\"]\').first
date = SDF::force_ascii(date_node.content.chomp.strip.reverse[0..17].reverse) if date_node
content = format_description(div.xpath(\'.//div[@class=\"content\"]\'))
end
解决方法
date_node = div.xpath(\'.//p[@class=\"author\"]\').first
如果div.xpath(\'.// p [@class = \“ author \”] \')为空,则date_node为nil。
date = SDF::force_ascii(date_node.content.chomp.strip.reverse[0..17].reverse) if date_node
# that hurted
date = SDF:::force_ascii(date_node.content.strip[-17,17])
如果date_node为nil,则不会执行date = SDF :: force_ascii(date_node.content.chomp.strip.reverse [0..17] .reverse)。