五個提升 Ruby 程式碼表達力與健壯性的慣用語:區塊解構賦值、Hash#fetch 安全取值、預設值 Hash、sort_by 施瓦茲轉換、String#present? (Rails) 語意化空值檢查。
def touch_down
yield [3, 7]
puts "touchdown!"
end
touch_down do |(first_down, second_down)|
puts "#{first_down} yards on the run"
puts "#{second_down} yards passed"
end
# 3 yards on the run
# 7 yards passed
# touchdown!
陣列自動解構對應區塊參數,可直接取首尾:first, *rest = [1,2,3] → first=1, rest=[2,3]。
items = { apples: 2, oranges: 3 }
items.fetch(:apples) # 2
items.fetch(:bananas) { |k| "No #{k}!" } # "No bananas!"
優於 items[:key] || default:能區分「鍵不存在」與「值為 nil/false」。
smash = Hash.new { |h, k| h[k] = "a #{k} just got SMASHED!" }
smash[:plum] = "cannot smash."
smash[:watermelon] # 自動執行 default proc,寫入並回傳
# => {:plum=>"cannot smash.", :watermelon=>"a watermelon just got SMASHED!"}
適用於備忘錄模式、費波納契遞迴快取等自動建構值場景。
cars = %w[beetle volt camry]
cars.sort_by { |car| car.size } # ["volt", "camry", "beetle"]
sort_by 只計算一次鍵值並快取,比 sort { |a,b| a.size <=> b.size } 快 (O(n log n) vs O(n log n) 但常數因子小)。
"brain".present? # true
"".present? # false
nil.present? # false
等同 !blank?。blank? 涵蓋 nil、空字串、空白字串、空陣列/雜湊。present? 語意更正向,適合 if user.name.present? 等防禦性編程。
| 方法 | 接收者 | 空值判定 |
|---|---|---|
nil? | 任意物件 | 只有 nil 為 true |
empty? | Array/Hash/String | 長度 0 |
blank? | 任意 (AS) | nil/空白/空集合 |
present? | 任意 (AS) | !blank? |
exists? | ActiveRecord::Relation | 資料庫是否存在記錄 |