透過類別(class)我們可以組織和產生許多具有相似屬性(attributes)和方法(methods)的物件。
# CheatSheet
class Customer
attr_reader :id, :name
attr_writer :id, :name
attr_accessor :id, :name
def initialize(id, name)
@id = id
@name = name
end
def self.greeting
end
private
protected
end
類別(class)
慣例上來說 class 會以大駝峰的方式命名(CamelCase ),例如 NewClass。
定義類別
- 使用關鍵字
class
來建立類別 - 透過關鍵字
initialize
來建立初始化物件的方法 - 以
@
開頭的方式建立「實例變數instance variable
」,每一個透過這個 class 建立的物件都會有自己的實例變數
class [ClassName]
# 在這裡定義 class variable
@@class_variable = [class_vairable]
# 在 initialize 中的程式會在 instantiation 的過程先被執行
def initialize([arg1], [arg2], ...)
# 一般來說 arguments 和 instance variable 的名稱會一樣
@arg1 = arg1
@arg2 = arg2
end
# Do something here ...
# instance method with instance variable,建立物件時就要放入參數
def get_custom_info
"id: #{@id}, name: #{@name}, addr: #{@addr}"
end
# instance method without instance variable,可以在建立物件後再放入參數
def greeting(name)
"Hello, #{name}. Welcome to our store"
end
end
透過類別建立物件
使用 Class.new('argument')
的方式來建立物件
class Person
def initialize(name)
@name = name
end
end
matz = Person.new('Yukihiro')
類別中的方法(methods in class)
類別中的方法主要可以分成實例方法(instance methods)
和類別方法(class methods
):
- 實例方法(instance method):能夠在實例上被使用的方法,大部分類別中的方法都是屬於實例方法。
- 類別方法(class method):能夠在類別(class)上被使用的方法
實例方法(instance method)
- 在 class 中直接建立的 method 就是 instance method
- 它可以被該 class 所建立的 instance 所使用,亦可代入參數
class Sample
# 這是實例方法(instance method)
def hello(name)
puts "Hello #{name}"
end
end
# use class to create objects with the method
instance = Sample.new # create a object with "new"
puts instance.methods # list all the method in the class
instance.hello "Kitty" # 這個 hello method,直接作為於實體 instance 上,稱作 instance method。
類別方法(class method)
- class method 指的是可以作用在 class 上的 method
# 這裡 .all 是作用在 Post class 上,所以稱作 class method
class PostsController < ApplicationController
def index
@posts = Post.all # all 是一個 class method
end
end