Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `super` in Ruby? [duplicate]

Tags:

super

ruby

When browsing the internet about ruby on rails, I see the word super. Can someone tell what it is and what it can do?

like image 252
endyey Es Avatar asked Jun 24 '15 06:06

endyey Es


2 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

like image 105
Abdul Baig Avatar answered Sep 28 '22 06:09

Abdul Baig


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

like image 25
Kranthi Avatar answered Sep 28 '22 06:09

Kranthi