萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 實用技巧:解構賦值、Hash#fetch、預設值 Hash、sort_by、present?

五個提升 Ruby 程式碼表達力與健壯性的慣用語:區塊解構賦值、Hash#fetch 安全取值、預設值 Hash、sort_by 施瓦茲轉換、String#present? (Rails) 語意化空值檢查。

1. 區塊參數解構賦值


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]。

2. Hash#fetch:安全取值與預設


items = { apples: 2, oranges: 3 }
items.fetch(:apples)                    # 2
items.fetch(:bananas) { |k| "No #{k}!" } # "No bananas!"

優於 items[:key] || default:能區分「鍵不存在」與「值為 nil/false」。

3. 預設值 Hash (Default Proc)


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!"}

適用於備忘錄模式、費波納契遞迴快取等自動建構值場景。

4. Array#sort_by:施瓦茲轉換


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) 但常數因子小)。

5. String#present? (Rails / ActiveSupport)


"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資料庫是否存在記錄
copyright © 萬盛學電腦網 all rights reserved