Ruby
, OOP
物件 = 狀態(名詞) + 行為(動詞)
在 Ruby 裡,幾乎什麼東西都是物件
那什麼不是物件?block
class Cat # 類別的命名規定 = 必須是常數
def eat(food)
puts "#{food} 好好吃!!"
end
end
kitty = Cat.new
kitty.eat "鮪魚罐頭" #=> 印出「鮪魚罐頭 好好吃!!」
nancy = Cat.new
nancy.eat "小魚餅干" #=> 印出「小魚餅干 好好吃!!」
把共同的特徵放在同一個分類(class)
與其說是繼承,不如說是分類
# 請建立一個小狗 Dog 類別及一個小貓 Cat 類別,並從都是繼承自動物 Animal 類別,而且都有實作走路 walk 及吃東西 eat 這兩個方法。
class Animal
def walk
# 實作
end
def eat
# 實作
end
end
class Dog < Animal
end
class Cat < Animal
end
class Cat
def initialize
puts "hello 你好"
end
end
kitty = Cat.new # 什麼都不用做,一出生就會打招呼
車輪餅有紅豆口味、奶油口味
傳給 new
方法的引數,後續會由 initialize
方法收
class Cat
def initialize(name, age)
@name = name
@age = age
end
end
kitty = Cat.new("kitty", 18)
# 實體方法 instance method
class Cat
def say_hello
puts "你好"
end
end
kitty = Cat.new
kitty.say_hello
# 類別方法 class method
# 方法前面加上 self
class Cat
def self.all
puts "全部的貓兒"
end
end
Cat.all
class CandidatesController < ApplicationController
def index
@candidates = Candidate.all # 類別方法
end
end
實體變數:@username
類別變數:@@username
實體變數存活在每個獨立的實體內
實體變數 = 在實體裡面可自由取用的變數
class Cat
def initialize(name)
@name = name
end
def say_my_name
return @name
end
end
kitty = Cat.new('kitty')
puts kitty.say_my_name # 會印出什麼?
# 實體變數在實體裡可自由取用,但在實體外就不行了
# Ruby 根本沒有屬性這回事
puts kitty.name # 會印出什麼?
class Human
def initialize(name)
@name = name
end
def name # getter
@name
end
def name=(new_name) # setter
@name = new_name
end
end
emily = Human.new('emily')
puts emily.name # emily
emily.name = 'KOKO'
attr_reader
/ attr_writer
/ attr_accessor
class Human
attr_accessor :name
def initialize(name)
@name = name
end
end
cc = CandidatesController.new # MVC 結構裡的 C
cc.action(:index) # 執⾏了某個 action
類別變數是 @@ 開頭的
類別變數 = 在類別方法裡面可取用的變數
class Cat
@@count = 0 # 類別變數
def initialize
@@count += 1
end
def self.counter
@@count
end
end
5.times {
Cat.new
}
p Cat.counter # 印出 5
Familiarity with Rakuten Travel QA Workflow (Hands-On Experience)
Dec 4, 2024A compilation of essential vocabulary gathered during my internship at Rakuten, with a sum of 94.
Mar 21, 2024create web applications in Ruby
Mar 1, 2024a Ruby Webserver Interface
Mar 1, 2024or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up