When browsing the internet about ruby on rails, I see the word super
. Can someone tell what it is and what it can do?
4 Answers
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

- 3,683
- 3
- 21
- 48
-
Not only constructor. You can call any parent class method, if the same method is present in subclass as well – Kranthi Jun 24 '15 at 06:25
-
sorry. just went in hurry updated thanks – Abdul Baig Jun 24 '15 at 06:26
Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.
def url=(addr)
super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr}
end

- 869
- 7
- 12
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()).

- 1,377
- 1
- 17
- 34
It was used to implement super class implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. And The search for a method body starts in the superclass of the object that was found to contain the original method.
def url=(addr)
super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr}
end

- 1,075
- 11
- 25