设置哈希值的操作

  • 哈希的交叉点

    要获取两个哈希的交集,请返回其值相等的共享密钥:

    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 }