class Parent
def self.parent_method
"#{self} called parent method"
end
def parent_method
"#{self} called parent method"
end
end
class Child < Parent
def parent_method
# call parent_method as
Parent.parent_method # self.parent_method gets invoked
# call parent_method as
self.class.superclass.parent_method # self.parent_method gets invoked
super # parent_method gets invoked
"#{self} called parent method" # returns "#<Child:0x00556c435773f8> called parent method"
end
end
Child.new.parent_method #This will produce following output
Parent called parent method
Parent called parent method
#<Child:0x00556c435773f8> called parent method
#=> "#<Child:0x00556c435773f8> called parent method"
self.class.superclass == Parent #=> true
Parent.parent_method
e self.class.superclass
chiamerà self.parent_method
(metodo di classe) di Parent
mentre super
chiama il (metodo esempio) parent_method
di Parent
.
fonte
2018-02-07 08:32:28
Questo non funziona. 'Child.new.other_method' restituisce' NoMethodError: super: nessun metodo superclasse 'other_method' per # '. La chiamata a 'super.method()' chiamerà solo 'method' su ciò che viene restituito dalla chiamata a' super' (che, in questo caso, non esiste). 'super' non è un riferimento alla' superclasse' di un'istanza. –
Cade
@Cade sei completamente corretto. Ho fatto la modifica per questo –
Anche chiamando 'super' chiameremo super con argomenti esatti che sono stati passati al metodo figlio. Se vuoi specificare gli argomenti puoi chiamarli super con loro: EG: 'def child (a, b); super; fine' vs 'def child (a, b); super (somevar); end' – Adam