ruby - 将散列动态添加到空数组
问题描述
我想使用 Nokogiri 来计算网站上出现的不同类属性的出现次数。为此,我正在实施广度优先搜索,每次遇到新的类属性时,我都想将其存储在具有唯一 ID 的哈希中。并且遇到每个相同的类属性,我想找到相同的哈希并增加它的出现键。
我正在尝试将所有这些哈希存储在一个数组中:
hashArray = []
new hash = {
id: uniqueID,
occurrence: 1,
className: node["class"]
}
理想情况下,我会在某个时候有这样的事情:
array = [
{id: 1, occurrences: 3, className: 'wrapper'},
{id: 2, occurrences: 5, className: 'media'}
]
每次搜索遇到新类时,如何初始化新的哈希以添加到数组中?
我试过这个:
hashArray << {id: uniqueID, occurrence: 1, className: node["class"]}
但是这种方法会导致数组一次只保存一个哈希值。
解决方案
我看到 ids 和 classNames 都是唯一的,如果您classNames
用作标识符,您可能不需要添加额外的id
. 这是一种应该像您描述的那样工作的方法:
# Initialise a Hash which values default to 0 (instead of nil)
occurrences = Hash.new(0)
# Example:
# occurrences['foo'] # => 0
# occurrences # => {}
# For all relevant nodes, count occurrences of their class names
occurrences[node["class"]] += 1
# Example:
# occurrences['bar'] += 1 # => 1
# occurrences['bar'] += 1 # => 2
# occurrences['foo'] += 1 # => 1
# occurrences # => {"bar"=>2, "foo"=>1}
# Add ids and format array, where ids are the index of the element
occurrences.map.with_index do |list, id|
{id: id, occurence: list.last, className: list.first}
end
# Example:
# => [{:id=>0, :occurence=>2, :className=>"bar"}, {:id=>1, :occurence=>1, :className=>"foo"}]
我希望你觉得这很有帮助。
推荐阅读
- python - 如何将 numpy 数组传递给 Flask API?
- jquery - 字段编辑器数据表货币
- html - 如何扩大下拉菜单的大小
- javascript - 如何使用 html css 和 javascript 在图标和文本的任一侧添加行?
- python - 在python中检测当前shell是否是powershell
- css - 如何在引导卡的标题旁边放置一个按钮?
- linux - 如何从脚本创建简单的日志文件
- python - pytest - 修补类不起作用,而是调用类
- python - Keras fit 打印出矩阵
- ios - UIImagePickerController 在照片库中错误地声明“没有照片或库”