require 'nokogiri'
require 'open-uri'
# Get a Nokogiri::HTML::Document for the page we’re interested in...
@doc = Nokogiri::XML(File.open("data.xml"))
# Search for nodes by css
ids = []
@doc.xpath('//itemid').each do |link|
ids << link.content
end
hash = {}
i = 0
@doc.xpath('//realestate').each do |link|
hash.store(link.to_s)
i+=1
#p hash
#sleep 2
#break if i ==1
end
p hash
一切正常。除了hash.store之外,我想要的是“用hash_id将数据存储在哈希中...谢谢
答案 0 :(得分:1)
我想也许你不想要哈希:你不是想把一个数据与另一个数据联系起来。相反,也许你正在寻找一套。尝试:
require 'set'
s = Set.new
# Later
s << link.to_s
或更简单:
require 'set'
links = Set.new( @doc.xpath('//realestate').map(&:to_s) )
答案 1 :(得分:0)
我不知道您的数据结构是什么,但这可以提供帮助:
> array = [[1, 'value1'], [2,'value2']]
=> [[1, "value1"], [2, "value2"], [2, "othervalue"]]
> hash = array.group_by { |e| e[0] }
=> {1=>[[1, "value1"]], 2=>[[2, "value2"], [2, "othervalue"]]}