Ruby post 匹配返回 Nil.. 就像它应该的那样

Ruby post match returning Nil.. like its supposed too

我的 while 循环不知何故被破坏了。我得到这个错误:

`block in scrape': undefined method `post_match' for nil
:NilClass   (NoMethodError)

它在遍历字符串后也像预期的那样返回 nil,并且它也像预期的那样填充数组,但是最后一次它命中 .post_match 它失败了,因为它是 nil.. 但是它应该是一个零..不知道该怎么办?我希望它只填充数组,然后在 parent_pic_first 为 nil 时退出循环。

parent_pic_first = /\"hiRes\":\"/.match(pic).post_match

   while parent_pic_first != nil

        parent_pic = URI.extract(parent_pic_first, ['http'])

        pic_list = []

        pic_list.push(parent_pic[0])

        parent_pic_first = /\"hiRes\":\"/.match(parent_pic_first).post_match

        end

错误不是 parent_pic_firstnil,问题是 /\"hiRes\":\"/.match(parent_pic_first)nil。您正在尝试对 nil 值调用方法 post_matchnil.post_match 显然行不通。

您需要添加一些检查以防止在 nil 上调用 post_match,所以像这样:

parent_pic_first = /\"hiRes\":\"/.match(pic).post_match

while parent_pic_first != nil
  parent_pic = URI.extract(parent_pic_first, ['http'])
  pic_list = []
  pic_list.push(parent_pic[0])
  regex_return = /\"hiRes\":\"/.match(parent_pic_first)
  if regex_return.nil?
    break
  else      
    parent_pic_first = regex_return.post_match
  end
end