2012-05-14 35 views
24
數組

假設我有此數組哈希:紅寶石容易尋找鍵值對的哈希

[ 
{"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"}, 
{"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"}, 
{"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"} 
] 

我如何解析「HREF」的哈希值,其中「產品」 =>「bcx」

有什麼簡單的方法可以在Ruby中做到這一點?

+1

編輯該問題,因爲它與JSON沒有任何關係。 –

回答

49
ary = [ 
    {"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"}, 
    {"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"}, 
    {"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"} 
] 

p ary.find { |h| h['product'] == 'bcx' }['href'] 
# => "https://basecamp.com/123456789/api/v1" 

請注意,這隻適用於元素存在。否則你將被調用訂閱操作[]nil,這將引發異常,所以你可能要檢查的是第一:

if h = ary.find { |h| h['product'] == 'bcx' } 
    p h['href'] 
else 
    puts 'Not found!' 
end 

如果需要執行該操作多次,你應該建立自己數據結構更快查找:

href_by_product = Hash[ary.map { |h| h.values_at('product', 'href') }] 
p href_by_product['campfire'] # => "https://company.campfirenow.com" 
p href_by_product['bcx']  # => "https://basecamp.com/123456789/api/v1" 
+3

對於散列建議+1。 –

+1

完美!不知道.find是你可以調用的一種方法。真的有幫助。 –

+6

@BrianW:Ruby編程規則1:學習'Enumerable'的方法。然後,再次學習它們。 –