| 類型 | 前綴 | 範疇 | 範例 |
| 區域變數 | 小寫/_ | 方法/區塊內 | name, _age |
| 實例變數 | @ | 單一物件 | @width, @height |
| 類別變數 | @@ | 類別及子類共享 | @@count |
| 全域變數 | $ | 全程式 | $global_var |
建構器與建立物件
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