class Customer
end
關鍵字 class 開頭,類別名首字大寫,駝峰式命名,end 結束。
| 類型 | 前綴 | 作用域 | 說明 |
|---|---|---|---|
| 區域變數 | 無 / _ | 方法內 | 方法結束即銷毀 |
| 實例變數 | @ | 物件實例 | 每個物件獨立,如 @width |
| 類別變數 | @@ | 類別及所有實例 | 共享資料,如 @@count |
| 全域變數 | $ | 整個程式 | 跨類別共享,慎用 |
cust1 = Customer.new
cust2 = Customer.new
new 為類別方法,會配置記憶體並呼叫 initialize。
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, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
class Sample
def hello
puts "Hello Ruby!"
end
end
obj = Sample.new
obj.hello # Hello Ruby!
def 定義,end 結束。return)。
class Box
def initialize(w, h)
@width, @height = w, h
end
# getter
def width; @width; end
def height; @height; end
# setter
def width=(v); @width = v; end
def height=(v); @height = v; end
end
box = Box.new(10, 20)
puts box.width # 10
box.width = 30
puts box.width # 30
可用 attr_accessor :width, :height 一鍵產生。