使用一种方法中声明的变量以另一种方法打开网页

Using variable declared in one method to open webpage in another method

我正在开发一个 CLI 项目,并尝试使用在另一种方法中声明的 url 变量打开网页。

def self.open_deal_page(input)
  index = input.to_i - 1
  @deals = PopularDeals::NewDeals.new_deals
  @deals.each do |info|
  d = info[index]
  @product_url = "#{d.url}"
  end
  @product_url.to_s
  puts "They got me!"
end

def self.deal_page(product_url)
  #self.open_deal_page(input)
  deal = {}
  html = Nokogiri::HTML(open(@product_url))
  doc = Nokogiri::HTML(html)
  deal[:name] = doc.css(".dealTitle h1").text.strip
  deal[:discription] = doc.css(".textDescription").text.strip
  deal[:purchase] = doc.css("div a.button").attribute("href")
  deal
  #binding.pry
end

但是我收到了这个错误。

  `open': no implicit conversion of nil into String (TypeError)

任何可能的解决方案?非常感谢您。

尝试在 open_deal_page 方法中 returning 你的 @product_url,因为现在你 returning puts "They got me!",还要注意你的 product_url 正在您的 each 块中创建,因此,它无法访问,请尝试先将其创建为空 string 然后您可以 return 它。

def open_deal_page(input)
  ...
  # Create the variable
  product_url = ''
  # Assign it the value
  deals.each do |info|
    product_url = "#{info[index].url}"
  end
  # And return it
  product_url
end

在您的 deal_page 方法中告诉 Nokogiri 打开您作为参数传递的 product_url。

def deal_page(product_url)
  ...
  html = Nokogiri::HTML(open(product_url))
  ...
end