Hi I am new to Ruby and I don’t understand why the call to a superclass’ static method doesn’t work with the super keyword, I get this kind of error
super: no superclass method `creer_adherent' for Adherent:Class
This is the superclass :
class Personne
...
def self.create(type)
print "Nom:"
nom = gets.chomp
print "Prénom:"
prenom = gets.chomp
if type == "adhérent"
personne = Adherent.new(nom,prenom)
else
personne = Auteur.new(nom,prenom)
end
@@liste.push(personne)
puts "#{type.capitalize} créé(e) : #{personne.nom} #{personne.prenom}"
end
end
Then the subclass:
class Adherent < Personne
...
def self.creer_adherent
super.create("adhérent")
end
end
main.rb
loop do
case menu
when "0"
break
when "1"
Adherent.creer_adherent
end
end
>Solution :
You have missunderstood what the super keyword in Ruby does and what its actually used for. super is used to call the method in the super class with the same name:
class Adherent < Personne
def self.create
super("adhérent")
end
end
It’s not a reference to to the super class. Thus when you’re calling super you’re calling creer_adherent on the superclass – and then you’re trying to call .create on its return value.
If you just want to call an inherited method you just call it:
class Adherent < Personne
def self.creer_adherent
create("adhérent")
end
end
If you really wanted call the method on the superclass explicitly you can:
class Adherent < Personne
def self.create
puts "This method should not be called"
end
def self.creer_adherent
superclass.create("adhérent")
end
end
However this isn’t something you would normally do.