Saturday, June 9, 2012

Ruby Classes

Classes are the blue prints used to create objects in a running system.

In contrast to Java, Ruby’s building blocks are classes, modules and mixins.

A class is the blueprint from which individual objects are created.

Classes are the basic template from which object instances are created.

A class is made up of a collection of variables representing internal state and methods providing behaviors that operate on that state.

Classes are defined in Ruby using the class keyword followed by a name. The name must begin with a capital letter and by convention names that contain more than one word are run together with each word capitalized and no separating characters (CamelCase). The class definition may contain method, class variable, and instance variable declarations as well as calls to methods that execute in the class context at read time, such as attr_accessor. The class declaration is terminated by the end keyword.

Example:
  class MyClass
    def some_method
    end
  end


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
 

Variables in a Ruby Class:

Ruby provides four types of variables:
  • Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _.
  • Instance Variables: Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.
  • Class Variables: Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
  • Global Variables: Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
 
 

Instance Variables

Instance variables are created for each class instance and are accessible only within that instance. They are accessed using the @ operator. Outside of the class definition, the value of an instance variable can only be read or modified via that instance's public methods.
Example:
  class MyClass
    @one = 1
    def do_something
      @one = 2
    end
    def output
      puts @one
    end
  end
  instance = MyClass.new
  instance.output
  instance.do_something
  instance.output
Surprisingly, this outputs:
nil 2
This happens (nil in the first output line) because @one defined below class MyClass is an instance variable belonging to the class object (note this is not the same as a class variable and could not be referred to as @@one), whereas @one defined inside the do_something method is an instance variable belonging to instances of MyClass. They are two distinct variables and the first is accessible only in a class method.

Class Variables

Class variables are accessed using the @@ operator. These variables are associated with the class hierarchy rather than any object instance of the class and are the same across all object instances. (These are similar to class "static" variables in Java or C++).
Example:
  class MyClass
    @@value = 1
    def add_one
      @@value= @@value + 1
    end
 
    def value
      @@value
    end
  end
  instanceOne = MyClass.new
  instanceTwo = MyClass.new
  puts instanceOne.value
  instanceOne.add_one
  puts instanceOne.value
  puts instanceTwo.value
Outputs:
 1
 2
 2

Class Instance Variables

Classes can have instance variables. This gives each class a variable that is not shared by other classes in the inheritance chain.
  class Employee
    class << self; attr_accessor :instances; end
    def store
      self.class.instances ||= []
      self.class.instances << self
    end
    def initialize name
      @name = name
    end
  end
  class Overhead < Employee; end
  class Programmer < Employee; end
  Overhead.new('Martin').store
  Overhead.new('Roy').store
  Programmer.new('Erik').store
  puts Overhead.instances.size    # => 2
  puts Programmer.instances.size  # => 1
For more details, see MF Bliki: ClassInstanceVariables

Class Methods

Class methods are declared the same way as normal methods, except that they are prefixed by self, or the class name, followed by a period. These methods are executed at the Class level and may be called without an object instance. They cannot access instance variables but do have access to class variables.
Example:
  class MyClass
    def self.some_method
      puts 'something'
    end
  end
  MyClass.some_method
Outputs:
 something

Instantiation

An object instance is created from a class through the a process called instantiation. In Ruby this takes place through the Class method new.
Example:
  anObject = MyClass.new(parameters)
This function sets up the object in memory and then delegates control to the initialize function of the class if it is present. Parameters passed to the new function are passed into the initialize function.
  class MyClass
    def initialize(parameters)
    end
  end

No comments:

Post a Comment