Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call a static superclass method from inside a subclass method

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading