当值是哈希值时更新特定的哈希键

时间:2018-08-21 18:02:38

标签: ruby hash nokogiri

我正在使用Nokogiri来计算网站上出现的不同类属性的出现次数。为此,我实现了广度优先搜索,每次遇到新的类属性时,我都希望将其类名存储为键,将出现次数存储为值(因此将值存储为散列的散列)。例如:

{"media"=>{:occurrences=>1, :id => uniqueID},
"wrapper"=>{:occurrences=>3, :id => uniqueID},
"container"=>{:occurrences=>3, :id => uniqueID}}

遇到每个相同的类属性,我想找到相同的哈希并增加其出现键。

allHash = {}
uniqueID = 0
if allHash.key?(descendent["class"]) 
   allHash.map do |key, v| #increment occurrences key if class is encountered during search
     if key.to_s == descendent["class"]
         v[:occurrences] += 1 
     end
   end
else #make a new hash key if class name is not in hash
  uniqueID += 1
  allHash[descendent["class"]] = {id: uniqueID, occurrences: 1}; 
end

因此,最终的哈希值可能会在搜索结束时更改为:

{"media"=>{:occurrences=>1, :id => uniqueID},
"wrapper"=>{:occurrences=>5, :id => uniqueID},
"container"=>{:occurrences=>10, :id => uniqueID}
"content"=>{:occurrences=>1, :id => uniqueID}}

我上面的代码无法增加出现次数。我该如何实施?

1 个答案:

答案 0 :(得分:2)

这里有一个更简单的方法:

unique_id = 0
hash = Hash.new {|h, k| h[k] = {id: (unique_id += 1), occurrences: 0} }

descendent_classes.each do |descendent_class|
  hash[descendent_class][:occurrences] += 1
end

结果(带有descendent_classes = ["a", "a", "b"]):

irb(main):031:0> hash
=> {"a"=>{:id=>1, :occurrences=>2}, "b"=>{:id=>2, :occurrences=>1}}