Could someone please explain what that "super" is?

R

Rubyist

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.
 
R

Ross Bamford

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: [:eek:ne, :two]
# => Some: [:eek:ne, :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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top