Ruby 值为哈希值时更新特定哈希键
我使用Nokogiri来计算出现在网站上的不同类属性的出现次数。为此,我实现了一个广度优先搜索,每当我遇到一个新的类属性时,我都希望将它的类名存储为一个键,并将出现的次数存储为一个值(因此是一个散列,其中的值是散列)。例如:Ruby 值为哈希值时更新特定哈希键,ruby,hash,nokogiri,Ruby,Hash,Nokogiri,我使用Nokogiri来计算出现在网站上的不同类属性的出现次数。为此,我实现了一个广度优先搜索,每当我遇到一个新的类属性时,我都希望将它的类名存储为一个键,并将出现的次数存储为一个值(因此是一个散列,其中的值是散列)。例如: {"media"=>{:occurrences=>1, :id => uniqueID}, "wrapper"=>{:occurrences=>3, :id => uniqueID}, "container"=>{:occurren
{"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}}
但是,我上面的代码无法增加出现次数。如何实现这一点?这里有一个更简单的方法:
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
结果(带有子类=[“a”、“a”、“b”]
):
这里有一个更简单的方法:
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
结果(带有子类=[“a”、“a”、“b”]
):
两个旁白。1:Ruby的一个约定是用于方法和变量的命名(例如,
allHash
而不是allHash
)。你不必遵守这个惯例,但99%以上的鲁比学生会遵守。2:当你给出一个例子时,要简洁但完整,所有元素都是有效的Ruby对象(如你所拥有的),将所需结果显示为Ruby对象,并为每个输入对象分配一个变量(例如,h={“media”=>…}
),这样读者就可以在答案和注释中引用这些变量,而不必定义它们。1:Ruby的一个约定是用于方法和变量的命名(例如,allHash
而不是allHash
)。你不必遵守这个惯例,但99%以上的鲁比学生会遵守。2:当你给出一个例子时,要简洁而完整,所有元素都是有效的Ruby对象(如你所拥有的),将期望的结果显示为Ruby对象,并为每个输入对象分配一个变量(例如,h={“media”=>…}
),这样读者就可以在答案和注释中引用这些变量,而不必定义它们。