設定雜湊值的操作

  • 雜湊的交叉點

    要獲取兩個雜湊的交集,請返回其值相等的共享金鑰:

    hash1 = { :a => 1, :b => 2 }
    hash2 = { :b => 2, :c => 3 }
    hash1.select { |k, v| (hash2.include?(k) && hash2[k] == v) } # => { :b => 2 }
    
  • 雜湊的聯合(合併):

    雜湊中的鍵是唯一的,如果在要合併的兩個雜湊中都出現鍵,則會覆蓋呼叫 merge 的雜湊中的鍵:

    hash1 = { :a => 1, :b => 2 }
    hash2 = { :b => 4, :c => 3 }
    
    hash1.merge(hash2) # => { :a => 1, :b => 4, :c => 3 }
    hash2.merge(hash1) # => { :b => 2, :c => 3, :a => 1 }