Skip to content
Tags

,

super

June 8, 2011

Usage of super

The way super handles arguments is as follows:

  • When you invoke super with no arguments Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. It automatically forwards the arguments that were passed to the method from which it’s called.
  • Called with an empty argument list – super()-it sends no arguments to the higher-up method, even if arguments were passed to the current method.
  • Called with specific arguments – super(a, b, c) – it sends exactly those argument
class Bicycle  
  attr_reader :gears, :wheels, :seats  
  def initialize(gears = 1)  
    @wheels = 2  
    @seats = 1  
    @gears = gears  
  end  
end  
  
class Tandem < Bicycle  
  def initialize(gears)  
    super 1 
    @seats = 2  
  end  
end  
t = Tandem.new(2)  
puts t.gears  
puts t.wheels  
puts t.seats  
b = Bicycle.new  
puts b.gears  
puts b.wheels  
puts b.seats  

Returns:

ruby-1.9.2-p180 :084 > mvim 
2
2
2
1
2
1
 => nil 

note: he might be wrong on the second bullet. ruby might be doing the exact opposite:
Advertisements

From → Uncategorized

Leave a Comment

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

%d bloggers like this: