Could someone please explain what that "super" is?

Hi,

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.

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}"
  end

  def ameth(one)
    "Some:ameth: #{one}"
  end
end

# 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}"
  end
end

# 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)
    super
    puts "Further: #{args.inspect}"
  end
end

# 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}"
    super(a1,a2,3)
  end

  # 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')
    "Last:ameth:#{s}"
  end
end

# 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}"
  end
end

SomeClass.new(1,2,3)

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

OtherClass.new(1,2,3)

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

FurtherClass.new(1,2,3)

# => Some: [1, 2, 3]
# => Further: [1, 2, 3]

l = LastClass.new(:one, :two)

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

puts l.ameth(55)

# => Last:ameth:Some:ameth: ten

Alternative.new(10,20)

# => Some: [10, 20, 3]
# => Alternative: [10, 20]

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

ยทยทยท

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

--
Ross Bamford - rosco@roscopeco.REMOVE.co.uk