Could someone please explain what that "super" is?


In order not to make an unnecessary crowd here, first I tried to learn
it myself, but I failed.
What is that “super” method? Could someone explain it please?

Thanks in advance.

On Thu, 2006-02-02 at 18:03 +0900, Rubyist wrote:

What is that “super” method? Could someone explain it please?

The ‘super’ commentary starts below. This is just a base-class.

class SomeClass
def initialize(one, two, three)
puts “Some: #{[one, two, three].inspect}”

def ameth(one)
“Some:ameth: #{one}”

1. When you override a method, you don’t ever have to consider the

inherited method if you don’t want to.

class OtherClass < SomeClass
def initialize(*args)
puts “Other: #{args.inspect}”

2. Sometimes, though, you’ll want to invoke the inherited method,

e.g. to make sure any initialization gets done. For this you

use the ‘super’ keyword, which says 'invoke the inherited method

of this name’. Without args, super passes this method’s arguments

to the superclass method.

class FurtherClass < SomeClass
def initialize(*args)
puts “Further: #{args.inspect}”

3. If you’re changing interfaces (with initialize) you might want to

pass up different arguments, which you can do by passing them

to super.

class LastClass < SomeClass
def initialize(a1,a2)
puts “Last: #{[a1,a2].inspect}”

3.5. You can of course get the result from super and massage it

as you need to when overriding methods.

def ameth(one)
s = super(‘ten’)

4. You don’t have to use super. This is mostly equivalent from

the user point of view (don’t know about internally).

class Alternative < SomeClass
alias :__old_init :initialize
def initialize(one,two)
__old_init(one,two, 3)
puts “Alternative: #{[one, two].inspect}”

=> Some: [1, 2, 3],2,3)

=> Other: [1, 2, 3],2,3)

=> Some: [1, 2, 3]

=> Further: [1, 2, 3]

l =, :two)

=> Last: [:one, :two]

=> Some: [:one, :two, 3]

puts l.ameth(55)

=> Last:ameth:Some:ameth: ten,20)

=> Some: [10, 20, 3]

=> Alternative: [10, 20]

There’s probably more stuff I forgot, but thats the basic gist of it.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs