【问题标题】:I am getting an error on line 13. It says that the `<<` method is undefined. how do I fix this? I am using Ruby我在第 13 行收到一个错误。它说 `<<` 方法未定义。我该如何解决?我正在使用红宝石
【发布时间】:2019-12-13 18:02:08
【问题描述】:

这是代码:

  def self.scrape_shoe
    @doc.css("div.product-card__body").each do |nike|
      name = nike.css("div.product-card__title").text.strip
      price = nike.css("div.product-card__price").text.strip
      shoes = self.new
      @all << shoes #having error here
    end 
  end 

这是错误:

Traceback (most recent call last):
        7: from bin/new_nikes:7:in `<main>'
        6: from /home/merkonical/new_nikes/lib/new_nikes/cli.rb:17:in `call'
        5: from /home/merkonical/new_nikes/lib/new_nikes/cli.rb:11:in `list_price'
        4: from /home/merkonical/new_nikes/lib/new_nikes/scraper.rb:9:in `scrape_shoe'
        3: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:237:in `each'
        2: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:237:in `upto'
        1: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:238:in `block in each'
/home/merkonical/new_nikes/lib/new_nikes/scraper.rb:13:in `block in scrape_shoe': undefined method `<<' for nil:NilClass (NoMethodError)

我可以为此做哪些可能的修复? 我正在研究 Ruby

【问题讨论】:

    标签: ruby command-line-interface


    【解决方案1】:

    我可以为此做哪些可能的修复?

    @allnilnil 没有名为 &lt;&lt; 的方法。确保@all 不是nil

    【讨论】:

    • 这个问题可能太宽泛了,但是什么是常见的事情导致它为零?
    • 有两个可能的原因:您将nil 分配给了变量,或者您没有为变量分配任何内容。
    • 你可以在@doc.css之前设置@all ||= []
    【解决方案2】:

    因为您将 shoes 对象推入未定义的实例变量而出现错误。

    在行动中定义@all

    def self.scrape_shoe 
      @doc.css("div.product-card__body").each do |nike|
          @all = []
          name = nike.css("div.product-card__title").text.strip
          price = nike.css("div.product-card__price").text.strip
          shoes = self.new
          @all << shoes #having error here
        end 
      end
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多