Introduction
Sometimes you want to use a method from a parent class inside a child class to keep or extend its behavior.
super # or super(arguments)
super inside a child method to call the same method from the parent class.super without arguments, it sends the same arguments the child method received.greet first, then adds its own message.class Parent def greet puts "Hello from Parent" end end class Child < Parent def greet super puts "Hello from Child" end end
add method with arguments and doubles the result.class Parent def add(x, y) x + y end end class Child < Parent def add(x, y) super(x, y) * 2 end end
super and adds "and Bark" to the result.class Animal def speak "Animal sound" end end class Dog < Animal def speak parent_sound = super "#{parent_sound} and Bark" end end dog = Dog.new puts dog.speak
super without arguments to forward them automatically.super without parentheses passes all arguments received by the child method.super() with empty parentheses, it calls the parent method without any arguments.super to call a parent class method from a child class.super helps reuse and extend parent behavior.super or let it forward the current ones automatically.super.super inside the child method calls the parent method with the same name.super inside the child method -> Option Dsuper to call parent method inside child [OK]parent.method_namethis with Ruby's selfsuper usage with argumentssuper arg1, arg2 or super(arg1, arg2). super arg1, arg2 uses the correct syntax without parentheses.class Parent
def greet(name)
"Hello, #{name} from Parent"
end
end
class Child < Parent
def greet(name)
super(name) + " and Child"
end
end
puts Child.new.greet("Alice")Child#greet method calls super(name), which calls Parent#greet(name) and returns "Hello, Alice from Parent".class Parent
def info
"Parent info"
end
end
class Child < Parent
def info
super()
puts "Child info"
end
end
Child.new.infosuper() calls the parent method with no arguments and returns "Parent info" but does not print it.class A
def message
"A"
end
end
class B < A
def message
"B" + super
end
end
class C < B
def message
super + "C"
end
end
puts C.new.messageC#message calls super which is B#message. B#message returns "B" + super which calls A#message returning "A".B#message returns "B" + "A" = "BA". Then C#message returns "BA" + "C" = "BAC".Pass the test and this pattern moves unknown