我正在针对我转换为哈希的API XML响应编写测试。然而,哈希是嵌套的,所以它似乎表现得像“提供”是关键,其他一切都是值。 (如下所示)
我希望能够访问此哈希中的键值对,以便我可以使用针对“Id”,“Count”等的rspec测试进行断言。谢谢
{"Offer"=>
{"href"=>"http://xyz",
"links"=>nil,
"Id"=>"1501507",
"Count"=>"5",
"Collected"=>"3",
"Status"=>"INPROGRESS"}}
答案 0 :(得分:1)
还有#dig
http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig
hash = {
"Offer"=> {
"href" => "http://xyz",
"links" => nil,
"Id" => "1501507",
"Count" => "5",
"Collected" => "3",
"Status" => "INPROGRESS"
}
}
puts hash.dig("Offer", "href")
# => http://xyz
答案 1 :(得分:0)
如果
hash = { "Offer"=> { "href" => "http://xyz",
"links" => nil,
"Id" => "1501507",
"Count" => "5",
"Collected" => "3",
"Status" => "INPROGRESS" } }
然后你可以使用这种表示法:
hash["Offer"]["href"] #=> "http://xyz"
或定义新哈希并使用常规哈希访问:
new_hash = hash["Offer"]
new_hash #=>
# { "href" => "http://xyz",
# "links" => nil,
# "Id" => "1501507",
# "Count" => "5",
# "Collected" => "3",
# "Status" => "INPROGRESS" }
new_hash["href"] #=> "http://xyz"