修改红宝石中的内部哈希

时间:2012-04-02 00:51:06

标签: ruby ruby-on-rails-3 hash

我正在尝试做以下事情;

我有一个哈希:{"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}}

我如何实现这一目标??

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

@h = {}

def addword word, doc
  inner = @h[word] || {}
  @h[word] = inner.merge(doc => (inner[doc] || 0) + 1)
  p [:hash_is_now, @h]
end

addword 'word1', 'doc1'
addword 'word1', 'doc2'
addword 'word2', 'doc2'
addword 'word1', 'doc1'
addword 'word2', 'doc2'
addword 'word2', 'doc3'