Classes

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


Defining a new class creates a new context nested in the enclosing class (class Object by default). Use the :: scope operator to access nested classes/modules and their constants or class methods.

 

 class MyClass     # name must be capitalized  C = "constant in MyClass"  class Inner  C = "in MyClass::Inner"  end end p MyClass::C     # constant in MyClass p MyClass::Inner::C   # in MyClass::Inner 

Existing classes, both built-in and newly defined, may be reopened and altered or extended at any time (even from within a C extension). Any existing instances will be updated with the new class definitions.

 

 class String     # existing built-in class  def my_method  puts "length: #{ length} " # implicit self  end end "abc123".my_method   # length: 6 

Any class may be subclassed; use the < symbol instead of parentheses. Ruby classes support single inheritance only. Modules are used to add shared functionality among classes (and objects) in place of using multiple inheritance.

Use initialize instead of __init__ for the "constructor." You do not need to pass in self for method definitions, since Ruby automatically binds it for you. Remember dot notation is for method calls only, so prepend instance variables with the @ symbol instead of self.

Note

Prepending a method name with self within a class definition is optional, since it will be called from within the context of the actual instance by default.


Use super to call the same-named method from the superclass (or an ancestor thereof).

 

 class MyString < String  def initialize(str)  @str = str    # instance variable  super      # call String#initialize(str)  end end 

Instantiate an object via the Class#new method. It will call any defined initialize method after allocating the object.

 

 mystr = MyString.new("text here") 

There is no equivalent to Python's __del__ hook, since Ruby does not use reference counting (see the section "Garbage Collection"). This may require you to organize your code differently.

Ruby has both class variables and class methods.

 

 class MyClass  @@class_variable = "Accessible to this class and subclasses"  MyConstant = "Globally accessible via MyClass::MyConstant"  def MyClass.class_method    # dot notation used in definition  puts "Available as method of the class object itself"  end end 

Ruby has no internal-use, class-private, or magic-attribute naming like Python's _*, __*, and __*__ forms. Ruby uses the __*__ form sometimes, but only to accommodate certain naming conflicts. For example, Object#__send__ is an alias for send.


   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net