【发布时间】:2010-10-19 21:03:26
【问题描述】:
我有一个像这样的 ruby 哈希
{ "stuff_attributes" => {
"1" => {"foo" => "bar", "baz" => "quux"},
"2" => {"foo" => "bar", "baz" => "quux"}
}
}
我想把它变成一个像这样的哈希
{ "stuff_attributes" => [
{ "foo" => "bar", "baz" => "quux"},
{ "foo" => "bar", "baz" => "quux"}
]
}
我还需要保留键的数字顺序,并且键的数量是可变的。上面是超级简化的,但我在底部包含了一个真实的例子。最好的方法是什么?
附言
也需要递归
就递归而言,这是我们可以假设的:
1) 需要操作的key会匹配/_attributes$/ 2) 哈希会有很多其他不匹配的键 /_attributes$/ 3)散列中的键总是一个数字 4) _attributes 哈希可以在任何其他键下的任何级别的哈希
这个散列实际上是控制器中创建操作的参数散列。这是需要使用此例程解析的真实示例。
{
"commit"=>"Save",
"tdsheet"=>{
"team_id"=>"43",
"title"=>"",
"performing_org_id"=>"10",
"tdsinitneed_attributes"=>{
"0"=>{
"title"=>"",
"need_date"=>"",
"description"=>"",
"expected_providing_organization_id"=>"41"
},
"1"=>{
"title"=>"",
"need_date"=>"",
"description"=>"",
"expected_providing_organization_id"=>"41"
}
},
"level_two_studycollection_id"=>"27",
"plan_attributes"=>{
"0"=>{
"start_date"=>"", "end_date"=>""
}
},
"dataitem_attributes"=>{
"0"=>{
"title"=>"",
"description"=>"",
"plan_attributes"=>{
"0"=>{
"start_date"=>"",
"end_date"=>""
}
}
},
"1"=>{
"title"=>"",
"description"=>"",
"plan_attributes"=>{
"0"=>{
"start_date"=>"",
"end_date"=>""
}
}
}
}
},
"action"=>"create",
"studycollection_level"=>"",
"controller"=>"tdsheets"
}
【问题讨论】: