2013-01-25 37 views
-4
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哈希裏面..謝謝如何陣列的內容存儲在一個哈希與hash_id

+2

通常人們會使用散列存儲鍵/值對。在你的情況下,你只存儲link.to_s的值。什麼是散列的需要? –

+0

我嘗試使用ruby代碼** hash.store(id,link.to_s)**,但它顯示錯誤。 –

+1

'hash.store(key,value)'與'hash [key] =(value)'相同。只需使用'[]'而不是'#store'。錯誤應該是你沒有提供鍵和值的參數。 – nicooga

回答

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"]]} 
+0

實際上,這是輸出,我需要同時打印哈希...請發送紅寶石代碼存儲在哈希中...我try.Hash.store(id.link.to_s) –

1

我想,也許你不想哈希:你不是想一塊與其他數據的關聯相反,也許你。試試:

require 'set' 

s = Set.new 

# Later 
s << link.to_s 

或者更簡單地說:

require 'set' 
links = Set.new(@doc.xpath('//realestate').map(&:to_s)) 
+1

+1爲此使用Set是方式去。它將保持唯一性,儘管OP可能應該強制URL爲小寫或大寫,並修剪會話ID並規範化查詢參數的順序,...和...和....總之它會打開一個全新的蠕蟲罐頭。 :-) –