Ruby 是純物件導向語言,所有事物皆為物件。本文深入探討類別定義、物件建立、initialize 建構器、實例變數、存取器(getter/setter)、實例方法、類別方法與類別變數,並提供完整可執行範例。
class Box
def initialize(w, h)
@width, @height = w, h
end
end
box1 = Box.new(10, 20)
box2 = Box.new(5, 15)
class Box
def initialize(w, h)
@width, @height = w, h
end
# getter
def width; @width; end
def height; @height; end
# setter
def width=(val); @width = val; end
def height=(val); @height = val; end
end
# 使用
box = Box.new(10, 20)
puts box.width # 10
box.width = 30
puts box.width # 30
class Box
attr_accessor :width, :height # 同時產生 getter/setter
# attr_reader :width # 唯讀
# attr_writer :width # 唯寫
end
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 initialize(w, h)
@width, @height = w, h
@@count += 1
end
def self.count
@@count
end
end
Box.new(1,2); Box.new(3,4)
puts Box.count # 2
class Shape
def area; 0; end
end
class Rectangle < Shape
def initialize(w, h); @w, @h = w, h; end
def area; @w * @h; end
end
class Circle < Shape
def initialize(r); @r = r; end
def area; Math::PI * @r**2; end
end
shapes = [Rectangle.new(10,5), Circle.new(7)]
shapes.each { |s| puts s.area } # 多型呼叫
重點: Ruby 類別本身也是物件(Class 類別的實例),支援開放類別(隨時新增方法)、混入模組等進階特性。