Ruby : How `super` method works; better understanding of super

What is the significance of super method

— does super method-call takes the params

— or we need to supply params explicitly

How `super` method works; internals

class ABC
  def print(num1, num2)
    puts %{ 
         num1: #{num1} 
         num2: #{num2} 
         num3: #{num3} }
  end
end
class Child < ABC
  def print(n1, n2)

    num3 = 30

    puts 'Some behavior added before actual method call;'
    super
  end
end

234

Scenario : When Super and child ‘s method have same param list

# in ' ~/test.rb' 
class ABC 
  def print(num1, num2, num3) 
    puts %{ 
         num1: #{num1} 
         num2: #{num2} 
         num3: #{num3} } 
  end 
end 
class Child < ABC 
  def print(num1, num2, num3) 
    puts 'Some behavior added before actual method call' 
    super( 
  end 
end
# In IRB session 
>> require '~/ test.rb ' 
2.1.1 :004 > child = Child.new 
 => #<Child:0x000000022a34e0> 
2.1.1 :005 > child.print(1,2,3) 
Some behavior added before actual method call; 
 
 num1: 1 
 num2: 2 
 num3: 3 
 => nil 
2.1.1 :006 >

When both have same num of param but different names

class ABC
  def print(num1, num2, num3)
    puts %{
         num1: #{num1}
         num2: #{num2}
         num3: #{num3} }
  end
end
class Child < ABC
  def print(n1, n2, n3)
    puts 'Some behavior added before actual method call;'
    super
  end
end

345

Now; different number of params

class ABC
  def print(num1, num2, num3)
    puts %{
         num1: #{num1}
         num2: #{num2}
         num3: #{num3} }
  end
end
class Child < ABC
  def print(n1, n2)
    n3 = 30
    puts 'Some behavior added before actual method call;'
    super
  end
end

456

Solution

class Child < ABC
  def print(n1, n2)
    n3 = 30
    puts 'Some behavior added before actual method call;'
    super(n1, n2, n3)
  end
end

567

Conclusion:

`super` method call is just a method call

  • It just calls the same method defined in ParentClass
  • Overriding method’s param-values are passed to the original method; if no param send while calling `super`
  • You can explicitly send params to `super` method call

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s