Super keyword in Ruby

I know this is late but:

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


no... super calls the method of the parent class, if it exists. Also, as @EnabrenTane pointed out, it passes all the arguments to the parent class method as well.


The super keyword can be used to call a method of the same name in the superclass of the class making the call.

It passes all the arguments to parent class method.

super is not same as super()

class Foo
  def show
   puts "Foo#show"
  end
end

class Bar < Foo
  def show(text)
   super

   puts text
  end
end


Bar.new.show("Hello Ruby")

ArgumentError: wrong number of arguments (1 for 0)

super(without parentheses) within subclass will call parent method with exactly same arguments that were passed to original method (so super inside Bar#show becomes super("Hello Ruby") and causing error because parent method does not takes any argument)


super calls a parent method of the same name, with the same arguments. It's very useful to use for inherited classes.

Here's an example:

class Foo
  def baz(str)
    p 'parent with ' + str
  end
end

class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => 'parent with test' \ 'child with test'

There's no limit to how many times you can call super, so it's possible to use it with multiple inherited classes, like this:

class Foo
  def gazonk(str)
    p 'parent with ' + str
  end
end

class Bar < Foo
  def gazonk(str)
    super
    p 'child with ' + str
  end
end

class Baz < Bar
  def gazonk(str)
    super
    p 'grandchild with ' + str
  end
end

Baz.new.gazonk('test') # => 'parent with test' \ 'child with test' \ 'grandchild with test'

If there's no parent method of the same name, however, Ruby raises an exception:

class Foo; end

class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => NoMethodError: super: no superclass method ‘baz’

Tags:

Ruby