Sto giocando con Ruby e sto imparando a conoscere le tecniche OO e l'ereditarietà e finalmente ho raggiunto un errore che mi ha eluso per un po '.Ruby Inheritance - Super Initialize che ottiene un numero errato di argomenti
persona Classe
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
programmatore Class (eredita da persona)
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
Poi nel mio script principale E 'in mancanza di questa linea
...
programmer = Programmer.new('Frank', 'Montero', 46, false, 20)
...
Con questa errore
./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
Un avviso speciale: la mia classe genitore ha preso senza argomenti, il suo bambino ha avuto uno. Continuavo a chiedermi perché il 'super' del bambino stava passando il suo argomento da' initialize' a 'Parent.initialize', quando ho capito che dovevo usare' super() ', che chiama esplicitamente la classe genitore con * nessun argomento *. – Droogans
@Doogans: thx! super() con parentesi esplicita differisce da super. – JCLL