少於 1 分鐘閱讀

加入

class Hash  
  def +(hash)  
    temp = Hash.new  
    self.each do |key, |  
      temp[key] = self[key] + hash[key] unless hash[key].nil?  
    end  
    hash.update(temp)  
    self.update(hash)  
  end  
end  

結果

hash = {"a" => 1, "b" => 1, "c" => 1, "d" => 1 }  
hash2 = {"a" => 2, "b" => 3, "d" => 4 }  
hash3 = hash + hash2  
puts hash3  # => {"a"=>3, "b"=>4, "c"=>1, "d"=>5}  

參考

  1. http://eric-gao.iteye.com/blog/558935

更新時間:

留言