Ruby继承 - 超级初始化获取错误的参数数量

时间:2011-10-07 15:49:52

标签: ruby oop inheritance constructor

我正在玩Ruby并学习OO技术和继承,我终于遇到了一段时间没有找到错误的错误。

人员类

class Person
    attr_accessor :fname, :lname, :age

    def has_hat?
        @hat
    end

    def has_hat=(x)
        @hat = x
    end

    def initialize(fname, lname, age, hat)
        @fname = fname
        @lname = lname
        @age = age
        @hat = hat
    end

    def to_s
        hat_indicator = @hat ? "does" : "doesn't"
        @fname + " " + @lname + " is " + @age.to_s + " year(s) old and " + hat_indicator + " have a hat\n"  
    end

    def self.find_hatted()
        found = []
        ObjectSpace.each_object(Person) { |p|
            person = p if p.hat?
            if person != nil
                found.push(person)              
            end
        }
        found
    end

end

程序员类(继承自人)

require 'person.rb'

class Programmer < Person
    attr_accessor :known_langs, :wpm

    def initialize(fname, lname, age, has_hat, wpm)
        super.initialize(fname, lname, age, has_hat)
        @wpm = wpm
        @known_langs = []
    end

    def is_good?
        @is_good
    end

    def is_good=(x)
        @is_good = x
    end

    def addLang(x)
        @known_langs.push(x)
    end


    def to_s
        string = super.to_s
        string += "and is a " + @is_good ? "" : "not" + " a good programmer\n"
        string += "    Known Languages: " + @known_languages.to_s + "\n"
        string += "    WPM: " + @wpm.to_s + "\n\n"
        string
    end

end

然后在我的主脚本中,这行失败了

...
programmer = Programmer.new('Frank', 'Montero', 46, false, 20)
...

出现此错误

./programmer.rb:7:in `initialize': wrong number of arguments (5 for 4) (ArgumentError)
        from ./programmer.rb:7:in `initialize'
        from ruby.rb:6:in `new'
        from ruby.rb:6:in `main'
        from ruby.rb:20

2 个答案:

答案 0 :(得分:23)

使用必需的参数调用super,而不是调用super.initialize。

super(fname, lname, age, has_hat)

答案 1 :(得分:3)

程序员初始化应该是 -

def initialize(fname, lname, age, has_hat, wpm)
    super(fname, lname, age, has_hat)
    @wpm = wpm
    @known_langs = []
end