我想说的是:
我有一个杂凑:{"word1" => {"doc1" => 1, "doc2" => 1}}
现在,当我在散列中插入一个新词时,我会传递给该词本身一个文档id,例如word2和doc2,它应该给我:

{"word1" => {"doc1" => 1, "doc2" =>1}, "word2" => {"doc2" => 1}}

如果我现在添加:word1和doc1,它应该给我:
{"word1" => {"doc1" => 2, "doc2" =>1}, "word2" => {"doc2" => 1}}

注:DOC1的值增加了1
对于word2和doc2
{"word1" => {"doc1" => 2, "doc2" =>1}, "word2" => {"doc2" => 2}}

另外,如果添加一个新的doc3来表示word2,它应该给我:
{"word1" => {"doc1" => 2, "doc2" =>1}, "word2" => {"doc2" => 2, "doc3" => 1}}

我怎么做到这一点!?

最佳答案

irb(main):005:0> words = Hash.new { |h,k| h[k] = Hash.new(0) }
irb(main):006:0> words["word1"]["doc1"] += 1
irb(main):007:0> words["word1"]["doc1"] += 1
irb(main):008:0> words["word2"]["doc2"] += 1
irb(main):009:0> words
=> {"word1"=>{"doc1"=>2}, "word2"=>{"doc2"=>1}}

当然,如果需要的话,可以将其封装到函数中。

10-07 18:55