继承类的参数错误

时间:2017-05-20 21:17:16

标签: ruby

我已按以下方式定义了一个类

class CraigslistPost < Nokogiri::XML::Element
  def initialize(html)
    if html.class != Nokogiri::XML::Element
      raise 'Must initialize with a Nokogiri XML Element'
    end
    super(html.name,html.document)
  end

当我尝试实例化它时,我得到一个参数错误..为什么我的新类需要2个参数?我只列出了一个。

[4] pry(main)> row.class
=> Nokogiri::XML::Element
[5] pry(main)> CraigslistPost.new(row)
ArgumentError: wrong number of arguments (1 for 2+)

更令人困惑的是,当我提供两个论点时,它说它想要1。

[6] pry(main)> CraigslistPost.new(row.name,row.document)
ArgumentError: wrong number of arguments (2 for 1)
from lib.rb:24:in `initialize`
[7] pry(main)> CraigslistPost.new(row)
ArgumentError: wrong number of arguments (1 for 2+)
from (pry):7:in `new'

1 个答案:

答案 0 :(得分:0)

您的班级最终继承自Nokogiri::XML::Node班级,initialize方法现在需要two parameters。您可能希望将类更改为:

class CraigslistPost < Nokogiri::XML::Element
  def initialize(html, document)
    if html.class != Nokogiri::XML::Element
     raise 'Must initialize with a Nokogiri XML Element'
    end  
    super(html.name, html.document)
  end  
end  

然后尝试以下内容:

file = Nokogiri::XML(File.read("path/to/document.xml"))
CraigslistPost.new(row, file)