geekelo / geekelo/dsa_practice
What is the difference between calling super and calling super()?
- Dominant language
- No language data
- Stars
- 1
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
In Ruby, `super` and `super()` are related but serve different purposes. Both are used in the context of inheritance and method overriding.
1. **`super`:** This is used within a method of a subclass to invoke the same-named method from its superclass. It passes the arguments that were passed to the current method in the subclass.
```ruby
class Parent
def example(arg)
puts "Parent class, arg: #{arg}"
end
end
class Child < Parent
def example(arg)
puts "Child class"
super # invokes the 'example' method in the Parent class with the same 'arg'
end
end
Child.new.example("Hello")
```
In this example, `super` is used to call the `example` method of the parent class with the argument passed to the method in the child class.
2. **`super()`:** This is used to invoke the same-named method from the superclass but without passing any arguments explicitly.
```ruby
class Parent
def example(arg)
puts "Parent class, arg: #{arg}"
end
end
class Child < Parent
def example(arg)
puts "Child class"
super() # invokes the 'example' method in the Parent class without passing 'arg'
end
end
Child.new.example("Hello")
```
Here, `super()` is used to call the `example` method of the parent class without passing the argument explicitly.
In summary, `super` without parentheses passes along the arguments implicitly, while `super()` explicitly calls the superclass method without passing any arguments. The choice between them depends on the specific requirements of the overridden method in the subclass.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.