Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Inheritance - Super Initialize getting wrong number of arguments

I'm playing with Ruby and learning about OO techniques and inheritance and I've finally hit an error that has eluded me for awhile.

Person Class

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

Programmer Class (inherits from Person)

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

Then in my main script It's failing on this line

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

With this error

./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
like image 711
jondavidjohn Avatar asked Oct 07 '11 15:10

jondavidjohn


2 Answers

call super with required params instead calling super.initialize.

super(fname, lname, age, has_hat)
like image 109
Naren Sisodiya Avatar answered Oct 04 '22 22:10

Naren Sisodiya


Programmer initialize should be -

def initialize(fname, lname, age, has_hat, wpm)
    super(fname, lname, age, has_hat)
    @wpm = wpm
    @known_langs = []
end
like image 39
Jayendra Avatar answered Oct 04 '22 22:10

Jayendra