# What is the difference between super() and super?
218
In Ruby, super and super() are used to call methods from the parent class, but they behave differently in terms of argument passing.
super
When you use super without parentheses, it passes all the arguments received by the current method to the parent method. This is useful when you want to ensure that the parent method receives the same arguments as the child method.
Example:
class Parent def greet(name) puts "Hello, #{name}!" end end class Child < Parent def greet(name) super puts "Welcome!" end end child = Child.new child.greet("Alice")
Output:
Hello, Alice! Welcome!
In this example, super passes the name argument to the greet method in the Parent class.
super()
When you use super() with parentheses, it calls the parent method without passing any arguments. This is useful when the parent method does not require any arguments or when you want to call the parent method without passing the current method’s arguments.
Example:
class Parent def greet puts "Hello from Parent!" end end class Child < Parent def greet(name) super() puts "Hello, #{name}!" end end child = Child.new child.greet("Alice")
Output:
Hello from Parent! Hello, Alice!
In this example, super() calls the greet method in the Parent class without passing any arguments, and then the Child class’s greet method continues with its own logic.
Summary
- super: Passes all arguments to the parent method.
- super(): Calls the parent method without passing any arguments.
This distinction allows you to control how arguments are handled when calling methods in the parent class.