[英]Searching in a subhash with Ruby on Rails
I have a hash of hashes like so: 我有这样的哈希哈希:
Parameters: {"order"=>{"items_attributes"=>{"0"=>{"product_name"=>"FOOBAR"}}}}
Given that the depth and names of the keys may change, I need to be able to extract the value of 'product_name' (in this example "FOOBAR") with some sort of search or select method, but I cannot seem to figure it out. 鉴于键的深度和名称可能会发生变化,我需要能够通过某种搜索或选择方法来提取“ product_name”的值(在本示例中为“ FOOBAR”),但我似乎无法弄清楚。
An added complication is that Params is (I think) a HashWithIndifferentAccess
更为复杂的是,Params(我认为)是
HashWithIndifferentAccess
Thanks for your help. 谢谢你的帮助。
Is this what you mean? 你是这个意思吗?
if params.has_key?("order") and params["order"].has_key?("items_attributes") then
o = params["order"]["items_attributes"]
o.each do |k, v|
# k is the key of this inner hash, ie "0" in your example
if v.has_key?("product_name") then
# Obviously you'll want to stuff this in an array or something, not print it
print v["product_name"]
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.