首页 > 解决方案 > 将散列动态添加到空数组

问题描述

我想使用 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"]}

但是这种方法会导致数组一次只保存一个哈希值。

标签: rubynokogiri

解决方案


我看到 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"}]

我希望你觉得这很有帮助。


推荐阅读