萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 類別與物件基礎觀念:定義、建構器、實例/類別/全域變數、存取器、建立物件

Ruby 物件導向核心概念:類別是物件的藍圖,物件是類別的實例。本文系統整理類別定義語法、initialize 建構器、四種變數範疇(區域、實例、類別、全域)、存取器與設定器、new 建立物件、自訂建構參數,並提供完整範例。

類別定義

class Customer
end

四種變數

建構器與建立物件

class Customer
  @@no_of_customers = 0
  def initialize(id, name, addr)
    @cust_id = id
    @cust_name = name
    @cust_addr = addr
    @@no_of_customers += 1
  end
end

cust1 = Customer.new("1", "John", "Wisdom Apartments")
cust2 = Customer.new("2", "Poul", "New Empire Road")

存取器與設定器

class Box
  def initialize(w, h)
    @width, @height = w, h
  end
  # 手寫 getter/setter
  def width; @width; end
  def width=(v); @width = v; end
  # 或使用 attr_accessor
  attr_accessor :width, :height
end

box = Box.new(10, 20)
puts box.width   # 10
box.width = 30
puts box.width   # 30

實例方法

class Box
  def initialize(w, h)
    @width, @height = w, h
  end
  def area
    @width * @height
  end
end

box = Box.new(10, 20)
puts box.area  # 200

類別方法

class Box
  @@count = 0
  def self.count
    @@count
  end
end

重點: Ruby 類別本身也是物件(Class 的實例),支援開放類別動態新增方法。

copyright © 萬盛學電腦網 all rights reserved
類型前綴範疇範例
區域變數小寫/_方法/區塊內name, _age
實例變數@單一物件@width, @height
類別變數@@類別及子類共享@@count
全域變數$全程式$global_var