透過類別(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
使用關鍵字 self 建立 class method:
###
# 透過 self 可以建立屬於該 class 的 method(class method)
# self 指的就是該物件本身(Hello)
# self.sayhi_class 等同於 Hello.sayhi_class
###
class Hello
def self.sayhi_class(name)
return "Hello, #{name}"
end
def sayhi_instance(name)
return "Hello, #{name}"
end
end
使用類別方法:
###
# :sayhi_class 直接作用在 Hello class 上,是 class method
# :sayhi_instance 作用在 Hello class 所建立的 greet instance 上,是 instance method
###
puts Hello.sayhi_class("Aaron") # class method
greet = Hello.new
puts greet.sayhi_instance("Aaron") # instance method
p greet.respond_to?(:sayhi_instance) # true,greet 中有方法 sayhi_instance(檢查該物件是否包含該方法)
p greet.respond_to?(:sayhi_class) # false,greet 中沒有方法 sayhi_class
p greet.class # Hello,greet 的 class 是 Hello
p greet.class.respond_to?(:sayhi_instance) # false,Hello 中沒有 sayhi_instance
p greet.class.respond_to?(:sayhi_class) # True,Hello 中有 sayhi_class
# puts greet.method(:sayhi_instance) # 檢查該物件的方法來自哪裡