Class names begin with a capital letter after the class keyword and terminate with the keyword end:
# Class class MySuperClass def mySuperMethod puts 'print something' end end # Class Inheritance: class MyExtendedClass < MySuperClass def extendedClassMethod puts 'print something from the extended class' end end myObject1 = MySuperClass.new myObject2 = MyExtendedClass.new
Methods (functions) start with a lowercase letter after the def keyword and terminate with the keyword end.
Creating objects Example:
class Dog def talk puts 'Woof!' end end class Terriers < Dog def howl puts 'wooooooooooooooo!!!' end end myDog = Terriers.new yourDog = Dog.new
Class Instance variables: A class variable begins with @@ and is shared by all objects created from a class. An instance variable begins with @ and can be accessed only by a specific object.
Constructors: When a class contains a method named initialize this will be automatically called when an object is created using the new method. It is a good idea to use an initialize method to set the values of an object’s instance variables.
class Dog @@num_dogs = 0 # This is a class method def Dog.showInfo puts 'TNumber of dogs = ' +@@num_dogs.to_s end def talk puts 'Woof! Name is ' + @name + ' I'm 1 of ' +@@num_dogs.to_s end def initialize ( aName ) @name = aName @@num_dogs += 1 end end class Terriers < Dog def howl puts @howl end def initialialize ( aName, aHowl ) super (aName) @howl = aHowl end end myDog = Dog.new ( 'Bob' ) yourDog = Terries.new ('Fido', 'wooooooooooooo!!!' ) myDog.talk yourDog.howl Dog.showInfo
Parenthesis are optional