Wednesday, November 6, 2013

Ruby: OOP (Basic)

class Person
  // This is a variable, that belongs to class
  // Like static variable in PHP
  @@class_variable = 0

  // This is a global variable
  $global_var

  // This is a constructor
  def initialize(name)
    // @name - class variable, name - local variable
    // @name will be available in whole class
    @name = name
    @class_variable += 1
  end

  // This is method, that belongs to class not to instance!
  // Like static method in PHP
  def self.class_method
  end
end

// This will create 2 instances of a Person class
andy = Person.new("Andy")
marrel = Person.new("Marrel")
// @@class_variable on this step will be equals to 2

Inheritance
// Class andy inherits all from class Person
class Andy < Person
  def initialize(name)
    // This will call parent initialize method
    super(name)
  end
end 

Infromation from: www.codeacademy.com 

No comments:

Post a Comment