2011-09-23 52 views
1

@hash是一個全球性的哈希值,看起來像:爲什麼不能用於遞歸讀取哈希?

@hash = { 
    "xmlns:xsi" =>"http://www.w3.org/2001/XMLSchema-instance", 
    "xsi:noNamespaceSchemaLocation"=>"merchandiser.xsd", 
    "header"  =>[{"merchantId"=>["35701"], 
    "merchantName" =>["Lingerie.com"], 
    "createdOn" =>["2011-09-23/00:33:35"]}], 
    "trailer"  =>[{"numberOfProducts"=>["0"]}] 
} 

而且我希望這個工作如果我叫下面像方法:

def amethod 
    hash_value("header", "merchantName") // returns "Lingerie.com" 
end 

def hash_value *attributes, hash = nil 
    hash = @hash unless hash 
    att = attributes.delete_at.first 
    attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first) 
end 
+0

至少不清楚(至少對我而言)是什麼問題;請添加失敗消息。 – jschorr

+0

我實際上在hash_value聲明中得到了一個語法錯誤,但它看起來對我來說 –

+0

請參閱提議的答案。 – jschorr

回答

1

在splat arg後面不能有默認參數。相反,要求將屬性列表作爲一個數組傳遞,如下所示:

def hash_value(attributes, hash = @hash) 
    return hash if attributes.empty? 
    hash_value(attributes[1..-1], hash[attributes.first].first) 
end 

p hash_value(["header", "merchantName"])   # => "Lingerie.com" 
p hash_value(["trailer", "numberOfProducts"]) # => "0" 
0

試試這個:

def hash_value(*attributes, hash) 
    hash = @hash unless hash 
    att = attributes.delete_at.first 
    attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first) 
end 
+0

我希望散列是一個可選參數。 –

+0

哦,對不起。你能發佈確切的錯誤信息嗎? – jschorr