When browsing the internet about ruby on rails, I see the word super
. Can someone tell what it is and what it can do?
super
method calls the parent class method.
for example:
class A
def a
# do stuff for A
end
end
class B < A
def a
# do some stuff specific to B
super
# or use super() if you don't want super to pass on any args that method a might have had
# super/super() can also be called first
# it should be noted that some design patterns call for avoiding this construct
# as it creates a tight coupling between the classes. If you control both
# classes, it's not as big a deal, but if the superclass is outside your control
# it could change, w/o you knowing. This is pretty much composition vs inheritance
end
end
If it is not enough then you can study further from here
when you are using inheritance if you want to call a parent class method from child class we use super
c2.1.6 :001 > class Parent
2.1.6 :002?> def test
2.1.6 :003?> puts "am in parent class"
2.1.6 :004?> end
2.1.6 :005?> end
=> :test_parent
2.1.6 :006 >
2.1.6 :007 > class Child < Parent
2.1.6 :008?> def test
2.1.6 :009?> super
2.1.6 :010?> end
2.1.6 :011?> end
=> :test_parent
2.1.6 :012 > Child.new.test
am in parent class
=> nil
2.1.6 :013 >
There are different ways we can use super(ex: super, super()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With