Programmering i Ruby

Den Pragmatiske Programmerers Veiledning

Forrige < Innhold ^
Neste >
klassen Class
Forelder: Module
Versjon: 1.6

Indeks:

inherited new new superclass


Classes in Ruby are first-class objects---each is an instance of class Class.

When a new class is created (typically using class Name ... end), an object of type Class is created and assigned to a global constant (Name in this case). When Name.new is called to create a new object, the new method in Class is run by default. This can be demonstrated by overriding new in Class:

class Class
   alias oldNew  new
   def new(*args)
     print "Creating a new ", self.name, "\n"
     oldNew(*args)
   end
 end

 class Name  end

 n = Name.new
produces:
Creating a new Name

klassemetoder
inherited aClass.inherited( aSubClass )

This is a singleton method (per class) invoked by Ruby when a subclass of aClass is created. The new subclass is passed as a parameter.

class Top
  def Top.inherited(sub)
    print "New subclass: ", sub, "\n"
  end
end

class Middle < Top end

class Bottom < Middle end
produces:
New subclass: Middle
New subclass: Bottom

new Class.new( aSuperClass=Object ) -> aClass

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).

instansmetoder
new aClass.new( [ args ]* ) -> anObject

Creates a new object of aClass's class, then invokes that object's initialize method, passing it args.

superclass aClass.superclass -> aSuperClass or nil

Returns the superclass of aClass, or nil.

Class.superclass » Module
Object.superclass » nil


Forrige < Innhold ^
Neste >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide".
Translation to norwegian by Norway Ruby User Group.
Copyright for the english original authored by David Thomas and Andrew Hunt:
Copyright © 2001 Addison Wesley Longman, Inc.
This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at
http://www.opencontent.org/openpub/).

(Please note that the license for the original has changed from the above. The above is the license of the original version that was used as a foundation for the translation efforts.)

Copyright for the norwegian translation:
Copyright © 2002 Norway Ruby User Group.
This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at
http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.