如何在我的 Nokogiri 文档中检索一组唯一的父节点?

How do I retrieve a unique set of parent nodes in my Nokogiri doc?

我将 RoR 5 与 Nokogiri 一起使用。我使用以下表达式从我的文档中获取子元素 ...

leaf_nodes = doc.xpath("//*[not(child::*)]")

我想检索这些子元素的父节点,所以现在,我正在做

    leaf_nodes.each_with_index do |leaf_node, index|
      node = leaf_node.parent
... process stuff

但这有点低效,因为我要多次重新处理一些父节点。有没有办法在我遍历所有内容之前检索一组唯一的父节点?

怎么样:

leaf_nodes.map(&:parent).uniq.each_with_index do |node, index|
  # Here node is already unique parent node
  # process stuff
end

leaf_nodes.map(&:parent).uniq 将提取父项并在迭代前为您提供唯一的父项。这样您就不必在同一个父元素上多次调用您的业务逻辑