当值为哈希值时更新特定的哈希键
Update a Specific Hash Key when Values are Hashes
我正在使用 Nokogiri 来计算网站上出现的不同 class 属性的出现次数。为此,我正在实施广度优先搜索,每次遇到新的 class 属性时,我都想将其 class 名称存储为键,将出现次数存储为值(因此哈希其中值是散列)。例如:
{"media"=>{:occurrences=>1, :id => uniqueID},
"wrapper"=>{:occurrences=>3, :id => uniqueID},
"container"=>{:occurrences=>3, :id => uniqueID}}
并且遇到每个相同的 class 属性我想找到相同的散列并增加它的出现键。
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}}
但是,我上面的代码无法增加出现次数。我该如何实施?
这里有一些更简单的方法:
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}}
我正在使用 Nokogiri 来计算网站上出现的不同 class 属性的出现次数。为此,我正在实施广度优先搜索,每次遇到新的 class 属性时,我都想将其 class 名称存储为键,将出现次数存储为值(因此哈希其中值是散列)。例如:
{"media"=>{:occurrences=>1, :id => uniqueID},
"wrapper"=>{:occurrences=>3, :id => uniqueID},
"container"=>{:occurrences=>3, :id => uniqueID}}
并且遇到每个相同的 class 属性我想找到相同的散列并增加它的出现键。
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}}
但是,我上面的代码无法增加出现次数。我该如何实施?
这里有一些更简单的方法:
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}}